Search code examples
phparraysfwrite

how to append data in existing array without overwrite whole array


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.


Solution

  • You have a few options:

    Good luck!