I have JSON format data something like this.
[
{
"user_id": "7",
"field": "1",
"value": "45"
},
{
"user_id": "10",
"field": "1",
"value": "53"
},
{
"user_id": "7",
"field": "2",
"value": "40"
},
{
"user_id": "10",
"field": "2",
"value": "45"
},
{
"user_id": "7",
"field": "3",
"value": "65"
},
{
"user_id": "10",
"field": "3",
"value": "69"
},
{
"user_id": "7",
"field": "4",
"value": "14"
},
{
"user_id": "10",
"field": "4",
"value": "13"
}
]
Now I want to convert it into Html table which will shows like this.
user_id 1 2 3 4
7 45 40 65 14
10 53 45 69 13
My json data is in $lika
My code is:
$arr = [];
$id = "";
foreach($lika as $value){
if($id === $value['user_id']){
echo "hfihf";
array_push($v, $value['value']);
}
else{
$v = [];
array_push($v, $value['user_id']);
array_push($v, $value['value']);
}
$arr[] = $v;
$id = $value['user_id'];
}
print_r($arr);
Please help me to do this.
You could create a new array with the user_id
as the array key and per key create an array which holds the values.
To create your table you could loop that array ($results
in the example) where the array key can be user for the column user_id
and loop the array with the values to create the additional columns.
$results = [];
foreach ($arrays as $value) {
$results[$value['user_id']][] = $value['value'];
}
To keep field_id as key in resulting array, and with an HTML printed from the results, purely for demonstrational purposes :)
$arr = [];
foreach($data as $v){
$arr[$v['user_id']][$v['field']] = $v['value'];
}
$i = 0;
echo '<table>';
foreach ($arr as $userId => $data) {
if ($i === 0) {
echo '<tr>';
echo '<td>user-id</td>';
foreach (array_keys($data) as $field) {
echo "<td>$field</td>";
}
echo '</tr>';
}
echo '<tr>';
echo "<td>$userId</td>";
foreach ($data as $field => $value) {
echo "<td>$value</td>";
}
echo '</tr>';
$i++;
}
echo '</table>';