tags:

views:

43

answers:

3
+1  Q: 

Search in array

$total is an multi dimension array:

Array (
    [1] => Array ( [title] => Jake [date] => date )
    [2] => Array ( [title] => John [date] => date )
    [3] => Array ( [title] => Julia [date] => date )
)

How to search for [title] value and give as result ID of an array?

If we search for Julia it should give 3 (ID is [3]).

Thanks.

+2  A: 
function get_matching_key($needle, $innerkey, $haystack) {
  foreach ($haystack as $key => $value ) {
    if ($value[$innerkey] == $needle) {
      return $key;
    }
  }

  return NULL;
}

$key_you_want = get_matching_key("Julia", "title", $total);
Dominic Rodger
array_keys($total) ?? Do you mean array_keys($haystack) ? And why not simply: foreach ($haystack as $key => $value) { if ($value[$innerkey] == $needle) { return $key; } }
Mark Baker
@Mark - thanks, my PHP's a bit rusty - sorry! Edited and made CW.
Dominic Rodger
+1  A: 

Ok sorry for my previous answer, didn't notice it was nested array. You may try this instead:

function recursiveArraySearch($haystack, $needle, $index = null)
{
    $aIt   = new RecursiveArrayIterator($haystack);
    $it    = new RecursiveIteratorIterator($aIt);

    while($it->valid())
    {
        if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) {
            return $aIt->key();
        }

        $it->next();
    }

    return false;
}

$array = array(3 => array('title' => 'Julia'));

$key = recursiveArraySearch($array, 'Julia');
echo $key;

Result:

3
Sarfraz
+1  A: 

posisible soultion:

function search_array($search,$array){
    $cnt=count($array);
    for($i=0;$i<$array;$i++){
        if($search==$array[$i]['title']){
            return $i;
        }
    }
}
xXx