Gus
Gus

Reputation: 93

Simple way to nest json in php

Should be very easy but I have been stuck on this. Getting data from Mysql with Json output that is missing a default nesting

$row->execute();
$item=array();
foreach($row as $rec)//foreach loop  
{   
    $testnab['Src']=$rec['src'];


array_push($item,$testnab);     


}

echo json_encode($item,JSON_PRETTY_PRINT);  

Result:

[ { "Src": "test1st" }, { "Src": "test3rd" } ]

I need the output to be:

[{"0": { "Src": "test1st" }},{"0": { "Src": "test3rd" }}] 

it is non-sequential with "0" being constant

Upvotes: 1

Views: 64

Answers (2)

mickmackusa
mickmackusa

Reputation: 47894

You can condense all of your declaration logic into one line and avoid the push call.

Nest your resultset row value inside a cast object.

Code: (Demo)

$resultset = [
    ['src' => 'test1st'],
    ['src' => 'test3rd'],
];

foreach ($resultset as $row) {   
    $item[] = (object)[['Src' => $row['src']]];
}

echo json_encode($item);

Output:

[{"0":{"Src":"test1st"}},{"0":{"Src":"test3rd"}}]

Upvotes: 1

Nick
Nick

Reputation: 147166

You can do this by creating an object with $testnab as a property value:

$item=array();
foreach($row as $rec)//foreach loop  
{   
    $testnab['Src']=$rec['src'];
    $o = new StdClass;
    $o->{'0'} = $testnab;
    array_push($item,$o);     
}
echo json_encode($item);

Output:

[{"0":{"Src":"test1st"}},{"0":{"Src":"test3rd"}}]

Upvotes: 1

Related Questions