tazo todua tazo todua - 3 months ago 12
PHP Question

Find ARRAY by to its values

I have a multi-dimensional array like so:

$a = array(
'potatoe'=> array(
'weight'=>24,
'label'=>'kon',
'year'=>2001,

),

'apple'=> array(
'weight'=>55,
'label'=>'krakat',
'year'=>1992,
)
);


I am looking for a way to searching the fruit name (with its values) when I only know weight is
55
and year is
1992
. How to do that?

Answer

You will have to iterate over it using foreach and test every element.

function findFruit($array,$weight, $year){
    foreach($array as $key => $fruit){
        if($fruit['weight'] == $weight && $fruit['year'] == $year ){
            return $key;
        }
    }
}

then, just use the function:

$theFruit = $a[findFruit($a,55,1992)];