Reputation: 29
Suppose the JSON data is like
$string = '{
"John": {
"status":"Wait",
"id":"001"
},
"Jennifer": {
"status":"Active",
"id":"002"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0,
"id":"003"
},
"Adam": {
"status":"Wait",
"age":71,
"count":10,
"progress":0.0029857,
"bad":0,
"id":"004"
}
}';
I need to group the array to the 'Status' of particular person. Like the key should become the 'Status' value and the id of persons inside array as the value of it.
Upvotes: 1
Views: 2064
Reputation: 6968
Here's one solution only if you're using PHP >= 5.5
$json_string = '{
"John": {
"status":"Wait",
"id":"001"
},
"Jennifer": {
"status":"Active",
"id":"002"
},
"James": {
"status":"Active",
"age":56,
"count":10,
"progress":0.0029857,
"bad":0,
"id":"003"
},
"Adam": {
"status":"Wait",
"age":71,
"count":10,
"progress":0.0029857,
"bad":0,
"id":"004"
}
}';
$json_arr = json_decode($json_string, true);
$result = array_column($json_arr, 'status', 'id');
Note: please note, I switched value and key from your desired end result, since the values in status
are not unique. This will have the effect that the values will be overwritten, thus you'll have only two elements in the result array. You can see the difference between my version and your requirement
Upvotes: 0
Reputation: 96
$jsonData = json_decode($YourJson, true);
$resultArr = array();
foreach($jsonData as $person => $value) {
foreach($value as $key => $val) {
$k = $value['status'];
$i = $value['id'];
$resultArr[$k][$i]['name'] = $person;
$resultArr[$k][$i][$key] = $val;
}
}
print "<pre>";
print_r($resultArr);
Upvotes: 1
Reputation: 29
I gone through that deep and found the answer for that..
$result = array();
foreach($json_a as $person => $value)
{
foreach($value as $key => $personal)
{
$key_s = $value['status'];
$id_s = $value['id'];
$result[$key_s][$id_s]['name'] = $person;
$result[$key_s][$id_s][$key] = $personal;
}
}
print "<pre>";
print_r($result);
Upvotes: 0