1

I am trying to do a search of a multidimensional array in order to append stuff to specific elements. I got a function that does a search and returns the specific part of that array, but I need the key so I can do $array[key] edits.

Function to get array

function arraySearch($array, $key, $value)
{
    $results = array();
    if (is_array($array))
    {
        if (isset($array[$key]) && $array[$key] == $value)
            $results[] = $array;
        foreach ($array as $subarray)
            $results = array_merge($results, arraySearch($subarray, $key, $value));
    }
    return $results;
}

I don't really know how to edit this to get the key from the array.

Steven
  • 13,250
  • 33
  • 95
  • 147
  • [Answered](http://stackoverflow.com/questions/5219871/multidimensional-array-search-using-php) – afuzzyllama Mar 20 '12 at 16:05
  • What kind of array are you passing to that function? The function is designed to find matching key/value pairs on nested arrays. If e.g. if finds a match under 4 levels of nesting, what would you expect to get as "the key"? – bfavaretto Mar 20 '12 at 16:06
  • It would just be a single level array. So array(0 => array( HERE)...) – Steven Mar 20 '12 at 16:06

1 Answers1

0

Try to use references "&"

function arraySearch($array, $key, $value)
{
   $results = array();
   if (is_array($array))
   {
       if (isset($array[$key]) && $array[$key] == $value)
           $results[] = &$array;
       foreach ($array as $subarray)
           $results = array_merge($results, arraySearch($subarray, $key, $value));
   }
   return $results;
}

And then you will be able to handle each $results entry as if it was directly in $array.

$searchResult = arraySearch($myArray, 'test', 'val');
foreach ($searchResult as &$item) {
  $item['nb']++;
}
Guile
  • 1,473
  • 1
  • 12
  • 20