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?

2
  • is the data structure fixed? i mean, are you going to have fixed(one that you have shown) structure of array? Commented Feb 14, 2013 at 8:31
  • @BhavikShah only the first array will change with foreach loop Commented Feb 14, 2013 at 8:32

4 Answers 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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

its better to add else after first if(isse($array[$name]))
why? that isn't good coding style.. you should prevent deep nesting
please help, m getting Fatal error</b>: Maximum function nesting level of '100' reached, aborting! when m trying to run that execute that function
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;
}

Comments

0

Use foreach to loop over the array.

foreach ($array AS $fruit) {
    if(isset($fruit['Apple'])) {
        echo $fruit['Apple']['Price'];
    }
}

Comments

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.