i have a problem here. so, i try to make nested array for my json using php and this is what im getting
[
{
"ID":"3301",
"NAME":"cust 01",
"ID2":"33"
},
{
"ID":"3301",
"NAME":"cust 01",
"ID2":"33"
}
]
but i want to make it like this
[
{
"ID":"3301",
"NAME":"cust 01",
"attribut":
[
{
"ID2":"33"
}
]
},
{
"ID":"3301",
"NAME":"cust 01",
"attribut":
[
{
"ID2":"33"
}
]
}
]
this is the code
//Query
$sql = 'select * from mytable';
$query = mysqli_query($con,$sql);
while($data=mysqli_fetch_array($query,MYSQLI_ASSOC))
$output[]=$data;
// json
echo json_encode($output);
can someone help me?
CodePudding user response:
Move the ID2
value into the nested array in the attribut
key before pushing onto the $output
array.
while($data=mysqli_fetch_array($query,MYSQLI_ASSOC)) {
$data['attribut'] = [['ID2' => $data['ID2']];
unset($data['ID2']);
$output[]=$data;
}
CodePudding user response:
like this?
$str = '[
{
"ID":"3301",
"NAME":"cust 01",
"ID2":"33"
},
{
"ID":"3301",
"NAME":"cust 01",
"ID2":"33"
}
]';
$arr = json_decode($str,true);
$ret =[];
foreach ($arr as $item){
$res = [];
$res['ID'] = $item['ID'];
$res['NAME'] = $item['NAME'];
$temp['ID2'] = $item['ID2'];
$res['attribut'][]=$temp;
$ret[] = $res;
}
var_dump(json_encode($ret));