I needed the nodes to be in this format:
"name": "Baixo Alentejo",
"color": "#f0e68d\r\n"
$nodes[]='name:'.$row['name'] ." ".'color:'.$row['color'] ;
With this code, it's like this:
"name:Baixo Alentejo color:#f0e68d\r\n",
I needed the nodes to be in this format:
"name": "Baixo Alentejo",
"color": "#f0e68d\r\n"
$nodes[]='name:'.$row['name'] ." ".'color:'.$row['color'] ;
With this code, it's like this:
"name:Baixo Alentejo color:#f0e68d\r\n",
If you want to generate JSON, you "must" format it as an array, using the indexes.
You can use several forms for this:
Form 1:
$array = ['nodes' => ["name" => "Baixo Alentejo", "color": "#f0e68d"]];
echo $json = json_encode($array);
Form 2:
$array['nodes']["name"] = "Baixo Alentejo";
$array['nodes']["color"] = "#f0e68d";
echo $json = json_encode($array);
Form 3:
$array['nodes'][] = ["name" => "Baixo Alentejo", "color" => "#f0e68d"];
echo $json = json_encode($array);
Result (in all cases):
{"nodes":{"name":"Baixo Alentejo","color":"#f0e68d"}}
The easiest way to adapt your code would be to change :
to =>
and remove this as string , resulting in:
$nodes['nodes'][] = ['name' => $row['name'], 'color' => $row['color']];
echo json_encode($nodes);
So?
$nodes[] = '"name": "' . $row['name'] . '", "color": "' . $row['color'] . '"';
//Array
//(
// [0] => "name": "Baixo Alentejo", "color": "#f0e68d\r\n"
//)
To format as JSON , use json_encode
:
$nodes['nodes']['name'] = $row['name'];
$nodes['nodes']['color'] = $row['color'];
$nodeEncode = json_encode($nodes);
$nodeDecode = json_decode($nodeEncode);
echo "json_encode \n";
var_dump($nodeEncode);
echo "json_decode \n";
foreach ($nodeDecode as $node){
echo $node->name . "\n";
echo $node->color . "\n";
}
// json_encode
// string(53) "{"nodes":{"name":"Baixo Alentejo","color":"#f0e68d"}}"
// json_decode
// Baixo Alentejo
// #f0e68d