如何匹配JSON中的键值对

时间:2015-06-25 11:39:33

标签: php arrays json

[
{"category":["30","32","33"],"type":"30 days","price":"100","ID":"0"},
{"category":["34","37","47"],"type":"30 days","price":"200","ID":1},
{"category":["46"],"type":"40 days","price":"100","ID":2}
]

在上面的JSON中,如何获得所有类型为30days的类别。

预期产出为。

$categories = array{0=>30,1=>32,2=>33,3=>34,4=>37,4=>47}  

3 个答案:

答案 0 :(得分:1)

您可以将array_walk用作

$json = '[
{"category":["30","32","33"],"type":"30 days","price":"100","ID":"0"},
{"category":["34","37","47"],"type":"30 days","price":"200","ID":1},
{"category":["46"],"type":"40 days","price":"100","ID":2}
]';
$arr = json_decode($json,true);
$categories = array();
array_walk($arr,function($v,$k)use(&$categories,$arr){
   if($v['type'] == "30 days"){
       $categories = array_merge($categories,$v['category']);
   }
});

答案 1 :(得分:0)

使用此:

$json = '[
{"category":["30","32","33"],"type":"30 days","price":"100","ID":"0"},
{"category":["34","37","47"],"type":"30 days","price":"200","ID":1},
{"category":["46"],"type":"40 days","price":"100","ID":2}
]';
$a = json_decode($json,true);
$categories = array();
foreach($a as $ar){
    if($ar['type'] == '30 days'){
        $categories = array_merge($categories,$ar['category']);
    }
}
print_r($categories);

输出:

Array ( [0] => 30 [1] => 32 [2] => 33 [3] => 34 [4] => 37 [5] => 47 ) 

http://sandbox.onlinephpfunctions.com/code/ea84f8a5baf5c231b4e9427b3b79f16bbc075401

答案 2 :(得分:0)

将一堆转换函数链接在一起:

$data =<<<JSON
[
{"category":["30","32","33"],"type":"30 days","price":"100","ID":"0"},
{"category":["34","37","47"],"type":"30 days","price":"200","ID":1},
{"category":["46"],"type":"40 days","price":"100","ID":2}
]
JSON;

$data = json_decode($data, true);

$x = call_user_func_array('array_merge', array_column(array_filter($data, function($row) {
    return $row['type'] == '30 days';
}), 'category'));

print_r($x);

另请参阅:array_filter() array_column() call_user_func_array()