0

M having multidimensional array and i want to check the key "Apple" if exist in it , if it is exist then i wan to get the Price of that Apple.

I have tried Array_key_exists() function , but it is applicable to only one dimensional array,

array(1) {
    [0]=>
        array(1) {
            ["Apple"]=>
                array(2) {
                    ["Color"]=>"Red"
                    ["Price"]=>int(50)
                }
            }
}

How can I get the price of the Apple if it exist in array?

4

4 回答 4

4

Use a recursive function to achive this

function getPrice($array, $name) {
    if (isset($array[$name])) {
        return $array[$name]["Price"];
    }

    foreach ($array as $value) {
        if (is_array($value)) {
            $price = getPrice($value, $name);
            if ($price) {
                return $price;
            }
        }
    }

    return false;
}
于 2013-02-14T08:30:50.330 回答
1

Just iterate (in a recursive way) over all yours array(s) and check for each if array_key_exists() or (maybe better) isset()

Just like

function myFinder($bigArray)
{
 $result = false;
 if(array_key_exist($key,$bigArray)) return $bigArray[$key];
 foreach($bigArray as $subArray)
 {
  if(is_array($subArray)
  {
   $result = $result or myFinder($subArray);
  }
 }
 return $result;
}
于 2013-02-14T08:33:50.880 回答
0

Use foreach to loop over the array.

foreach ($array AS $fruit) {
    if(isset($fruit['Apple'])) {
        echo $fruit['Apple']['Price'];
    }
}
于 2013-02-14T08:31:28.363 回答
0
$rows=array(
         array(
               'Apple'=>array('Color'=>'Red', 'Price'=>50)
              )
        );

function get_price($rows, $name)
{
   foreach($rows as $row) {
     if(isset($row[$name])) return $row[$name]['Price'];
   }
   return NULL;
}

echo get_price($rows, 'Apple');
于 2013-02-14T08:36:40.113 回答