php 如何在现有数组中追加数据而不覆盖整个数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12893246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to append data in existing array without overwrite whole array
提问by Shashank
This is my code, in this code, I am reading an existing array through a function read_from_json, which convert JSON to array, now from remote data I am getting new dataso I have to append those data in my existing array without overwriting the whole array. Like if I am getting an id, it searches using the in_array function, if it is not found then sending a message to it, and then append the only specific entry to existing array. There is a problem due to foreach iteration so it overwrites all array, what else can I do. Please have a look at this code:
这是我的代码,在这段代码中,我正在通过函数 read_from_json 读取现有数组,该函数将 JSON 转换为数组,现在从远程数据中获取新数据,因此我必须将这些数据附加到现有数组中,而不会覆盖整个数组大批。就像我得到一个 id 一样,它使用 in_array 函数进行搜索,如果没有找到,则向它发送一条消息,然后将唯一的特定条目附加到现有数组中。由于 foreach 迭代存在问题,因此它会覆盖所有数组,我还能做什么。请看一下这段代码:
$read_data = $this->read_from_json( 'xyz.json' );
foreach ( $projects_id_tickcamp as $tick_id => $base_id ) {
if ( !$this->in_array( $base_id['base_id'], $read_data ) ) {
echo '<b>do post message function for ' . $tick_id . ' ' . $base_id['base_id'] . '</b><br />';
$i = count( $read_data );
while ( $i >= count( $base_id['base_id'] ) ) {
echo 'post message start' .'<br />';
$i++;
break;
$projects_id_tickcamp[$tick_id]['message_id'] = 1;
}
//echo 'posted message id of ' . $base_id['basecamp_id'] . '<br />';
} else {
echo 'do nothing' . '<br />';
//return false;
}
}
//echo 'write data if id similar' . '<br />';
$this->write_to_json( 'xyz.json', $projects_id_tickcamp );
return $projects_id_tick;
The output of the above code looks like:
上面代码的输出如下所示:
Array
(
[125434] => Array
(
[base_id] => 1306755
)
[127354] => Array
(
[base_id] => 1287834
)
)
if a new id fetch from remote then id writes only in last place of array.
如果从远程获取新 id,则 id 仅写入数组的最后一个位置。
回答by Barry Chapman
You have a few options:
您有几个选择:
- array_push()
- array_merge( $curr_array, $new_array )
- $array[] = $newValue
- 数组推送()
- array_merge( $curr_array, $new_array )
- $array[] = $newValue
Good luck!
祝你好运!
回答by Manoj
after returning another value,using array_merge will fix this.
返回另一个值后,使用 array_merge 将解决此问题。
example:
例子:
$result_array=array_merge($arr1,$arr2);
回答by Flame
If you want to append something to a PHP array, you can use $myArray[] = "new value"
如果要将某些内容附加到 PHP 数组,可以使用 $myArray[] = "new value"

