Search code examples
phparrayssub-array

retrieving sub array based on sub sub value


OK, so I have an array that looks like this:

$countries = array();
$countries['CA'] = array('name'=>'Canada','currency'=>array('code'=>'CAD','format'=>'$#')); 
$countries['US'] = array('name'=>'USA','currency'=>array('code'=>'USD','format'=>'$#'));
$countries['AR'] = array('name'=>'Argentina','currency'=>array('code'=>'ARS','format'=>'$#'));
$countries['AW'] = array('name'=>'Aruba','currency'=>array('code'=>'AWG','format'=>'ƒ#'));

If I have the value "ARS", how would I retrieve the entire "AW" sub array?

edit: sorry, I need the "format" next to it.


Solution

  • You can use array_filter to return only values from the array which match the code you're looking for:

    $code = 'ARS';
    $results = array_filter($countries, function($country) use ($code) {
        return $country['currency']['code'] == $code;
    });
    

    $results will be an array containing zero or more elements, depending on how many matches were found. For the example array in your question, this would be:

    array(array('name'=>'Argentina','currency'=>array('code'=>'ARS','format'=>'$#')));
    

    You can loop over the results, or get the first one with $country = reset($results); which will return false if no countries matched your code.

    If you only expect a maximum of one match, or only want to get the first match, then you can loop over the array and break as soon as you find what you're looking for:

    $found_country = null;
    foreach ($countries as $country) {
        if ($country['currency']['code'] == $code) {
            $found_country = $country;
            break;        
        }
    }