I'm trying to return two arrays from a PHP with a JSON object.
Here's my PHP code:
$return = array();
$return += array('val1' => '1',
'val2' => '2',
'val3' => '3');
$tab = array();
for($i=0; $i<3; $i++)
{
$val = "table1 " . $i;
array_push($tab, array('tab1' => $val));
}
$return += $tab;
$tab = array();
for ($i = 0; $i < 5; $i++) {
$val = "table2 " . $i;
array_push($tab, array('tab2' => $val));
}
$return += $tab;
echo json_encode($return);
and here's my JS code:
console.log("val1=" + data.val1);
console.log("val2=" + data.val2);
console.log("val3=" + data.val3);
for(var i=0; i<3; i++)
console.log("tab1_" + i + "=" + data[i].tab1);
for (var i = 0; i < 5; i++)
console.log("tab2_" + i + "=" + data[i].tab2);
And here's what I get on console:
val1=1
val2=2
val3=3
tab1_0=table1 0
tab1_1=table1 1
tab1_2=table1 2
tab2_0=undefined
tab2_1=undefined
tab2_2=undefined
tab2_3=undefined
tab2_4=undefined
Why can't I add to arrays to the JSON object? What am I doing wrong? Thank you for your help.
The +
and +=
operators often don't work as expected when combining arrays. If the keys in the second array are already present in the first array, they will be skipped. Your two $tab
arrays both had keys 0, 1, and 2 so they weren't being added. Instead, change
$return += $tab;
to
$return = array_merge($return, $tab);
which should finally be something like this:
$return = array();
$return += array('val1' => '1',
'val2' => '2',
'val3' => '3');
$tab = array();
for($i=0; $i<3; $i++)
{
$val = "table1 " . $i;
array_push($tab, array('tab1' => $val));
}
$return = array_merge($return, $tab);
$tab = array();
for ($i = 0; $i < 5; $i++) {
$val = "table2 " . $i;
array_push($tab, array('tab2' => $val));
}
$return = array_merge($return, $tab);
echo json_encode($return);
and the result should be what you are expecting:
{
"0": {
"tab1": "table1 0"
},
"1": {
"tab1": "table1 1"
},
"2": {
"tab1": "table1 2"
},
"3": {
"tab2": "table2 0"
},
"4": {
"tab2": "table2 1"
},
"5": {
"tab2": "table2 2"
},
"6": {
"tab2": "table2 3"
},
"7": {
"tab2": "table2 4"
},
"val1": "1",
"val2": "2",
"val3": "3"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.