LS_
LS_

Reputation: 7129

PHP add/remove values from array created by json

I have an array that looks like this after using json_decode() on a response from a Json webservice:

    [11] => Array
        (
            [0] => 80B37803-6278-5351-BC7A-D3A2FBFF8AA7
            [1] => test
            [2] => 
        )

    [12] => Array
        (
            [0] => 70B37803-6278-5351-BC7A-D3A2FBFF8AA8
            [1] => test 2
            [2] => 
        )

    [13] => Array
        (
            [0] => 90B37803-6278-5351-BC7A-D3A2FBFF8AA9
            [1] => test 3
            [2] => 
        )

To print the array I use the following code:

echo '<pre>'; print_r($responseArticle); echo '</pre>';

How can I edit this kind of array in order, for example, to add a 3rd row or delete one of the already exsisting row?

Upvotes: 1

Views: 57

Answers (3)

joy d
joy d

Reputation: 418

To add in some info for N key:

$responseArticle[N] = array('80B37803-6278-5351-BC7A-D3A2FBFF8AA7', 'testN', '');

To delete info stored in N key:

if(isset($responseArticle[N]) {
 unset($responseArticle[N]);
}

Here N can be any number, say 3 as you have asked in the question.

Upvotes: 0

jameshwart lopez
jameshwart lopez

Reputation: 3131

to add another value of an array is to use array_push and to delete it you can use unset. See the example below.

<?php 
        $json_array[11] = array('80B37803-6278-5351-BC7A-D3A2FBFF8AA7','test','');
        $json_array[12] = array('70B37803-6278-5351-BC7A-D3A2FBFF8AA8','test 2','');
        $json_array[13] = array('90B37803-6278-5351-BC7A-D3A2FBFF8AA9','test 3','');

        array_push($json_array, array('90B37803-6278-5351-BC7A-D3A2FBFF8AA9','test 4',''));
        echo '<pre>';print_r($json_array);echo '</pre>';

        unset($json_array[14]);
        echo '<pre>';print_r($json_array);echo '</pre>';
    ?>

Upvotes: 1

Parth Chavda
Parth Chavda

Reputation: 1829

$newArray = json_decode($json_data);

add inner data adding a column for 11 number of row

$newArray[11][4] = 'this is the 4th column';

for delete

unset($newArray[11][4]);

for adding row

$newArray[lastindex] = array('90B37803-6278-5351-BC7A-D3A2FBFF8AA9','test4','');

for delete row

  unset($newArray[index]);

Upvotes: 1

Related Questions