Reputation: 21
[
{"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}
]
in the above JSON, how to get all the category which has type: 30days.
Expected Output as.
$categories = array{0=>30,1=>32,2=>33,3=>34,4=>37,4=>47}
Upvotes: 1
Views: 124
Reputation: 173642
Just chain a bunch of transformation functions together:
$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);
See also: array_filter()
array_column()
call_user_func_array()
Upvotes: 0
Reputation: 21422
You can use array_walk
as
$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']);
}
});
Upvotes: 1
Reputation: 9430
Use this:
$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);
Output:
Array ( [0] => 30 [1] => 32 [2] => 33 [3] => 34 [4] => 37 [5] => 47 )
http://sandbox.onlinephpfunctions.com/code/ea84f8a5baf5c231b4e9427b3b79f16bbc075401
Upvotes: 0