使用键值从多维数组中提取值

时间:2016-02-12 15:45:42

标签: php arrays json multidimensional-array

我想知道是否有人可以帮助我通过键值而不是数组值从数组中提取值。

$json = json_decode($stock, true);
print_r($json);
$sims = $json['stock'][1]['sims'];

foreach ($sims as $sim)
{
    echo nl2br($sim . "\n");
}

print_r($json)的输出是:

Array ( [stock] => Array (
[0] => Array
( [operator] => ECL [sims] => Array
( [0] => 8944122616994 [1] => 89650264517182 [2] => 894412265075 [3] => 894412 ) )
[1] => Array
( [operator] => JT [sims] => Array
( [0] => 89445023065 [1] => 894156673081 [2] => 8944501 [3] => 89445027 ) ) ) )

看来有时我想要的数据不在数组1中,因此我想根据"[operator] => JT"提取它我一直在尝试各种各样的想法,但它似乎永远不会起作用。

3 个答案:

答案 0 :(得分:3)

您可以使用array_searcharray_column

来帮助它

这将为您提供多维数组键

$key = array_search("JT", array_column($json['stock'], 'operator'));

然后你可以做

$sims = $json['stock'][$key]['sims'];
print_r($sims) //this will print desired array

答案 1 :(得分:0)

尝试:

$json = json_decode($stock, true);

foreach($json["stock"] as $arr){
    echo $arr["operator"]."\n";
    foreach($arr["sims"] as $sim){
        echo $sim."\n";
    }
    echo "\n";
}

这将输出(例如):

  

ECL
  8944122616994个
  89650264517182
  894412265075
  894412

     

JT
  89445023065
  894156673081
  8944501个
  89445027

答案 2 :(得分:0)

写一个这样的函数:

function getSims(array $array) {
    $sims = [];

    foreach ($array as $data) {
        if ($data['operator'] == 'JT') {
            return $data['sims'];
        }
    }
    // here you could also throw an exception or return something else
    return [];
}

并像这样使用它:

$json = json_decode($stock, true);
$sims = getSims($json['stock']);