如何在现有数组中追加数据而不覆盖整个数组 [英] how to append data in existing array without overwrite whole array

查看:154
本文介绍了如何在现有数组中追加数据而不覆盖整个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,在此代码中,我正在通过read_from_json函数读取现有数组,将JSON转换为数组,现在是从远程数据中获取新数据,因此我必须将这些数据附加到我现有的数组中,而不要覆盖整个数组。就像我得到一个ID一样,它使用in_array函数进行搜索,如果找不到它,则向其发送消息,然后将唯一的特定条目附加到现有数组中。由于foreach迭代存在问题,因此它会覆盖所有数组,我还能做什么。请看下面的代码:

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 data so 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_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;

以上代码的输出如下:

Array
(
    [125434] => Array
        (
            [base_id] => 1306755
        )

    [127354] => Array
        (
            [base_id] => 1287834
        )

)

如果从远程获取新的id,则id仅写在数组的最后一个位置。

if a new id fetch from remote then id writes only in last place of array.

推荐答案

您有一些选择:

祝你好运!

这篇关于如何在现有数组中追加数据而不覆盖整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆