how to append data in existing array without overwrite whole array [closed]

六月ゝ 毕业季﹏ 提交于 2019-12-07 12:18:15

问题


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;

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.


回答1:


You have a few options:

  • array_push()
  • array_merge( $curr_array, $new_array )
  • $array[] = $newValue

Good luck!




回答2:


after returning another value,using array_merge will fix this.

example:

$result_array=array_merge($arr1,$arr2);



回答3:


If you want to append something to a PHP array, you can use $myArray[] = "new value"



来源:https://stackoverflow.com/questions/12893246/how-to-append-data-in-existing-array-without-overwrite-whole-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!