2

I have a parent array that contains years as 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2005

and on the other hand i am getting result from my db that returns year and count , Now, what i am trying to do is that an array being populated as per parent array (years) for the results being generated for something like following:

Results being Generated by sql
+----------------+
 YEAR   |   Count
 1994   |    16
 1995   |    16
 1996   |    16
+----------------+

The array should store following values as per check if sql query results contains result for year of parent array or not

1994   |    16
1995   |    16
1996   |    16
1997   |    0
1998   |    0
1999   |    0
2000   |    0
2005   |    0

Thanks, Note I want the reuslt to be generated in an array as mentioned above because i have to pass these values to highcharts (For generating graph)

1
  • 2
    Post some code please so we know the current variable names that you use Commented Dec 30, 2012 at 13:03

1 Answer 1

2

Depends how $years_db is built, Here an example:

$years       = array(1994, 1995, 1996, 1997, 1998, 1999, 2000, 2005);
$years_db    = array(1994 => 16, 1995 => 16, 1996 => 16);

$array_temp = array();
foreach ($years as $year)
{
    /* if (in_array($year, array_keys($years_db)))
     * $array_temp[$year] = $years_db[$year];
     * else
     * $array_temp[$year] = 0;
     */

    // @gumbo suggestion is more efficient. THX!
    $array_temp[$year] = isset($years_db[$year]) ? $years_db[$year] : 0;
}

output of $array_temp:
array (
  1994 => 16,
  1995 => 16,
  1996 => 16,
  1997 => 0,
  1998 => 0,
  1999 => 0,
  2000 => 0,
  2005 => 0,
)
Sign up to request clarification or add additional context in comments.

1 Comment

Better use array_key_exists($year, $years_db) or isset($years_db[$year]) instead of in_array($year, array_keys($years_db)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.