Re: array_search and multi-dimensional arrays

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



List Manager wrote:
jonathan wrote:


I'd like to return the first key value in the following array such that England would return 1 rather than 3 which is the second key value. Any help would be greatly appreciated.

$c[1][]="Vietnam";
$c[1][]="China";
$c[1][]="Thailand";
$c[1][]="England";
$c[2][]="USA";
$c[2][]="Japan";


print_r($c);
// Array ( [1] => Array ( [0] => Vietnam [1] => China [2] => Thailand [3] => England ) [2] => Array ( [0] => USA [1] => Japan ) )

foreach($c as $row)
{
    echo array_search("England",$row);
}
// prints 3

-jonathan

--PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

give this a shot

<?php
function findIndexof($ar, $str) {
 foreach($ar AS $k => $v) {
   if ( is_array($v) ) {
     $val = findIndexof($v, $str);
     if( $val !== false ) {
       return $val;
     }
   } elseif ( strtolower($v) == strtolower($str) ) {
     return $k;
   }
 }
 return FALSE;
}

$c[1][] = "Vietnam";
$c[1][] = "China";
$c[1][] = "Thailand";
$c[1][] = "England";
$c[2][] = "USA";
$c[2][] = "Japan";

echo findIndexof($c, 'Vietnam');
?>

You should be able to search arrays of any depth

Hope this woks for you.

Jim

Or, a lot easier:
foreach($c as $key=>$row) {
 if(false !== array_search("England",$row)) {
    echo $key;
  }
}

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux