在 for 循环中,我正在合并数组,但在循环末尾只添加最后一个。$result = json_decode($response['body']);if(isset($result->{'items'})) { $count = count($result->{'items'});} else { $count = 0;}$json = [];if($count > 0) { for ($i=0; $i < $count; $i++) { if (isset($result->{'items'}[$i]->{'title'})) { $title = $result->{'items'}[$i]->{'title'}; $title_array = array('title' => $title); $json = array_merge($json, $title_array); } }}
2 回答

杨__羊羊
TA贡献1943条经验 获得超7个赞
您的问题是您正试图将包含的数组'title' => 'x'
与另一个包含'title' => 'y'
. 由于它们都包含相同的键,因此第二个会覆盖第一个。您需要更改此行:
$json = array_merge($json, $title_array);
至
$json[] = $title_array;
然后你会得到一个带有标题的数组数组,例如
[['title' => 'x'], ['title' => 'y']]

智慧大石
TA贡献1946条经验 获得超3个赞
代替:
$json = array_merge($json, $title_array);
通过以下:
array_push($json, $title_array); // it will push the the new array to `$json`
- 2 回答
- 0 关注
- 205 浏览
添加回答
举报
0/150
提交
取消