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?
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;
}
Use foreach to loop over the array.
foreach ($array AS $fruit) {
if(isset($fruit['Apple'])) {
echo $fruit['Apple']['Price'];
}
}
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;
}
$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');