0

Possible Duplicate:
Find values in multidimensional arrays

This is my array, it contains an array of key value pairs.

[
   {
    valueA: 0,
    valueB: 0,
    day: "2010-04-09"
   },
   {
    valueA: 0,
    valueB: 0,
    day: "2010-04-10"
   }
]

I want to check if a certain value is at key "day" in any index (and if so, modify the values in that node)

is there an efficient way to do this with the in_array method?

otherwise I guess I would do it with a nested for loop

Community
  • 1
  • 1
CQM
  • 42,592
  • 75
  • 224
  • 366

3 Answers3

1

Not with the in_array function, but you can use array_filter:

// assuming $myarray = Array(......);
if( $found = array_filter($myarray,function($a) {return $a['day'] == '2010-04-10';})) {
    // you can now do something with the $found array
}

EDIT: Just saw your comment about using PHP 5.2.2 - this version doesn't support anonymous functions, so you will need this:

if( $found = array_filter($myarray,create_function('$a','return $a["day"] == "2010-04-10";')))
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

Loop only once and set date as key

$hash = array();
foreach ( $array as $v ) {
    $hash[$v['day']][] = $v;
}

Now you can use isset which is O(1) rather than O(n) all the time

if (isset($hash['2010-04-10'])) {
    echo "Here";
}
Baba
  • 94,024
  • 28
  • 166
  • 217
  • yeah, this is the route I am going now kind of. Mainly just the part about setting date as a key too. Thanks for your contributions – CQM Feb 04 '13 at 17:38
0

I would use array_map instead. This will allow you to modify the array when the keys match. array_filter just allows population of an array.

If you create a new method (using 5.2 and create_function) you can specify your logic in it. Then, pass that into the array_map method to get your new, processed array.

In my example below, I'm checking to see if the 'day' of the variable is '2010-04-10' - and if so, changing valueA of that particular array to 1.

$processArrayFunction = create_function('$a',
                                        'if ($a["day"] == "2010-04-10") {
                                            $a["valueA"] = 1;
                                        }
                                        return $a;
                                        ');

$newArray = array_map($processArrayFunction, $sourceArray);
Aaron Saray
  • 1,178
  • 6
  • 19
  • I still feel like I will be needing to pass variables into the create_function method. What if my keys are dynamically generated – CQM Feb 04 '13 at 17:22
  • Since the second parameter of create_function() is a string, you could splice in any variable you'd want when you defined that function. Or, you could define create_function() to have two parameters in the first string (the second being your variable)... and then pass that after $sourceArray. If this doesn't make sense, please let me know and I'll generate a code sample. – Aaron Saray Feb 05 '13 at 00:36