I'm trying to format an array where if it doesn't have the particular id, I'm trying to assign the data as 0. But it's not happening.
The problem here I'm facing is when I tried adding $dataset[$label['id']]['data'][] = 0
if it's empty or not found inside labels object from the main array $array
, it's not working.
I have this following array:
$array = '[{
"id": 26,
"name": "Tactical",
"count": 127,
"labels": {
"2": {
"id": 2,
"risk": "Medium",
"count": 80
},
"1": {
"id": 1,
"risk": "Low",
"count": 39
},
"3": {
"id": 3,
"risk": "High",
"count": 8
}
}
},
{
"id": 14,
"name": "Citizen Safety",
"count": 116,
"labels": {
"4": {
"id": 4,
"risk": "Extreme",
"count": 7
},
"2": {
"id": 2,
"risk": "Medium",
"count": 103
},
"3": {
"id": 3,
"risk": "High",
"count": 6
}
}
},
{
"id": 25,
"name": "Strategic",
"count": 79,
"labels": {
"2": {
"id": 2,
"risk": "Medium",
"count": 40
},
"1": {
"id": 1,
"risk": "Low",
"count": 11
},
"3": {
"id": 3,
"risk": "High",
"count": 28
}
}
}
]';
Here the snippet of code that I'm trying for
$labels = [];
$dataset = [];
foreach ($array as $key => $value) {
$labels[] = $value['name'];
foreach ($value['labels'] as $label) {
if (empty($dataset[$label['id']])) {
$dataset[$label['id']] = [
'label' => $label['risk'],
'backgroundColor' => '#FF9534'
];
$dataset[$label['id']]['data'] = [];
$dataset[$label['id']]['data'][] = $label['count'];
} else {
if (empty($dataset[$label['id']]['data'])) {
$dataset[$label['id']]['data'][] = 0;
} else {
$dataset[$label['id']]['data'][] = $label['count'];
}
}
}
}
$dataset = [
'labels' => $labels,
'datasets' => $dataset,
];
echo json_encode($dataset);
die;
And I'm getting the below output
{
"labels": [
"Tactical",
"Citizen Safety",
"Strategic"
],
"datasets": {
"2": {
"label": "Medium",
"backgroundColor": "#FF9534",
"data": [
80,
103,
40
]
},
"1": {
"label": "Low",
"backgroundColor": "#FF9534",
"data": [
39,
11
]
},
"3": {
"label": "High",
"backgroundColor": "#FF9534",
"data": [
8,
6,
28
]
},
"4": {
"label": "Extreme",
"backgroundColor": "#FF9534",
"data": [
7
]
}
}
}
But the actual output I would like to have is the below one
{
"labels": [
"Tactical",
"Citizen Safety",
"Strategic"
],
"datasets": {
"2": {
"label": "Medium",
"backgroundColor": "#FF9534",
"data": [
80,
103,
40
]
},
"1": {
"label": "Low",
"backgroundColor": "#FF9534",
"data": [
39,
0,
11
]
},
"3": {
"label": "High",
"backgroundColor": "#FF9534",
"data": [
8,
6,
28
]
},
"4": {
"label": "Extreme",
"backgroundColor": "#FF9534",
"data": [
0,
7,
0
]
}
}
}
I mean when I loop through the labels from the $array
array objects when any array object doesn't have the label object (like medium, low, high, extreme) I'm trying to assign count as 0 which is not happening in the response. Can someone help me with what am I'm missing here?
You can check the execution of code here https://sandbox.onlinephpfunctions.com/code/398b2d1aa892e898a72fb053e981519e3215a053