简体   繁体   中英

How to filter this multidimensional array?

This is my input array:

INPUT :

$input["a"]["b"]["UK"] = 96 ;
$input["a"]["c"]["UK"] = 69 ;
$input["a"]["bp"]["USA"] = 29 ;
$input["a"]["c"]["USA"] = 59 ;
$input["a"]["dd"]["UK"] = 31 ;
$input["a"]["cg"]["UK"] = 38 ;

I want to get a new array that will contain only ["USA"]. So output have to be..............

OUTPUT :

$output["a"]["bp"]["USA"] = 29 ;
$output["a"]["c"]["USA"] = 59 ;

IS IT POSSIBLE ?

This will work.

$input["a"]["b"]["UK"]   = 96 ;    
$input["a"]["c"]["UK"]   = 69 ;
$input["a"]["bp"]["USA"] = 29 ;
$input["a"]["c"]["USA"]  = 59 ;
$input["a"]["dd"]["UK"]  = 31 ;
$input["a"]["cg"]["UK"]  = 38 ;
$tempResult = array();

foreach($input as $key => $value){

    foreach($value as $subkey => $subvalue){

        foreach($subvalue as $finalkey => $finalvalue){

            if($finalkey == 'USA') {

                $tempResult[$key][$subkey][$finalkey] = $finalvalue;
            }
        }
    }
}

echo '<pre>';print_r($tempResult);echo '</pre>';
<?php
$input["a"]["b"]["UK"] = 96 ;
$input["a"]["c"]["UK"] = 69 ;
$input["a"]["bp"]["USA"] = 29 ;
$input["a"]["c"]["USA"] = 59 ;
$input["a"]["dd"]["UK"] = 31 ;
$input["a"]["cg"]["UK"] = 38 ;

foreach($input as $x => $y) {
    foreach($y as $zz => $r) {
        foreach($r as $xxx => $j) {
            if($xxx == "USA") {
                echo($j);
            }
        }
    }
}
?>

user2944231's is cleaner I think but ya

The most straight forward answer is to use foreach loops:

$input=array();
$output=array();
$input["a"]["b"]["UK"] = 96 ;
$input["a"]["c"]["UK"] = 69 ;
$input["a"]["bp"]["USA"] = 29 ;
$input["a"]["c"]["USA"] = 59 ;
$input["a"]["dd"]["UK"] = 31 ;
$input["a"]["cg"]["UK"] = 38 ;

//get the level 0 keys (e.g. a) level 0 value (e.g array("b"=>array("UK"=>96)) )
foreach($input as $level_0_key => $level_0_value)
{
    //get the level 1 keys (e.g. b) level 1 value (e.g array("UK"=>96) )
    foreach($level_0_value as $level_1_key => $level_1_value)
    {
        //get the level 2 keys (e.g. UK) level 2 value (e.g 96)
        foreach($level_1_value as $level_2_key => $level_2_value)
        {
            if($level_2_key=="USA")
            {
                $output[$level_0_key][$level_1_key][$level_2_key]=$level_2_value;
            }
        }
    }
}
print_r($output);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM