我的代码: 情景1
$newarray = array();
foreach($rows as $k => $v)
{
$newarray[$k] = $v;
$newarray['newitem'] = 'Add this to existing object';
}
echo json_encode($newarray);
我也试过这个: 情景2
$newarray = array();
foreach($rows as $k => $v)
{
$newarray[$k] = $v;
$newarray[$k]['newitem'] = 'Add this to existing object';
}
echo json_encode($newarray);
在方案1中,仅在第一个对象之后添加键值对。它没有循环。 在方案2中,我得到HTTP ERROR 500
我在这里做错了什么?
更新
现有产出:
[{"pid":"123","date":"2016-08-23 08:08:40","post_title":"AHHH"},{"pid":"223","date":"2016-08-23 08:08:40","post_title":"wwwwAHHH"},{"pid":"223","date":"2016-08-23 08:08:40","post_title":"xxxAHHH"}]
必需输出:
[{"pid":"123","date":"2016-08-23 08:08:40","post_title":"AHHH","newkey":"new value1"},{"pid":"223","date":"2016-08-23 08:08:40","post_title":"wwwwAHHH","newkey":"new value2"},{"pid":"223","date":"2016-08-23 08:08:40","post_title":"xxxAHHH","newkey":"new value3"}]
答案 0 :(得分:2)
您可以创建一个包含所需内容的临时数组,然后将其添加到newarray中,以创建临时数组,添加新数据和现有数据,然后将其添加到newarray
$newarray = array();
foreach($rows as $k => $v)
{
$t = $v;
$t['newitem'] = 'Add this to existing object';
$newarray[$k] = $t;
}
echo json_encode($newarray);
编辑:
现在我知道$rows
中的JSON字符串是什么,这是你想做的事情。您不能通过JSON字符串进行操作,必须先将其转换为PHP数据结构,然后再添加新数据,然后将其转换回JSON字符串
$rows = '[{"pid":"123","date":"2016-08-23 08:08:40","post_title":"AHHH"},{"pid":"223","date":"2016-08-23 08:08:40","post_title":"wwwwAHHH"},{"pid":"223","date":"2016-08-23 08:08:40","post_title":"xxxAHHH"}]';
$objArray = json_decode($rows);
$newarray = array();
foreach($objArray as $v)
{
$v->newitem = 'Add this to existing object';
$newarray[] = $v;
}
print_r($newarray);
echo json_encode($newarray);
$newArray
现在是
Array
(
[0] => stdClass Object
(
[pid] => 123
[date] => 2016-08-23 08:08:40
[post_title] => AHHH
[newitem] => Add this to existing object
)
[1] => stdClass Object
(
[pid] => 223
[date] => 2016-08-23 08:08:40
[post_title] => wwwwAHHH
[newitem] => Add this to existing object
)
[2] => stdClass Object
(
[pid] => 223
[date] => 2016-08-23 08:08:40
[post_title] => xxxAHHH
[newitem] => Add this to existing object
)
)
新的JSON字符串将是
[ {"pid":"123",
"date":"2016-08-23 08:08:40",
"post_title":"AHHH",
"newitem":"Add this to existing object"
},
{"pid":"223",
"date":"2016-08-\u200c\u200b23 08:08:40",
"post_title":"wwwwAHHH",
"newitem":"Add this to existing object"
},
{"pid":"223",
"date":"2016\u200c\u200b-08-23 08:08:40",
"post_title":"xxxAHHH",
"newitem":"Add this to existing object"
}
]
答案 1 :(得分:1)
在场景1中,每次都为同一个数组键分配一个不同的值$ v,因此它被覆盖(并最终成为传递给foreach的最后一行的值): / p>
$newarray['newitem'] = 'Add this to existing object';
场景2位于正确的位置,但需要稍微改变。在场景2中,您将添加一个包含$ v的数组,但随后会立即覆盖它:
$newarray[$k] = $v;
$newarray[$k]['newitem'] = 'Add this to existing object';
您需要为项目提供单独的密钥,因此解决方案可能是使用“旧项目”。键将初始值分配给:
$newarray[$k]['olditem'] = $v;
$newarray[$k]['newitem'] = 'Add this to existing object';
您可以使用许多解决方案,具体取决于您希望如何构建阵列,但关键原则是确保值具有单独的键,以便它们不会相互覆盖。