Home > database >  how to edit array in php
how to edit array in php

Time:12-28

I have array $array["rlist"] that outputs:

Array (
    [0] => Array ( [0] => test1 )
    [1] => Array ( [0] => test2 )
    [2] => Array ( [0] => test3 )
    [3] => Array ( [0] => test4 )
    [4] => Array ( [0] => test5 ) 
)

When I try to edit like so:

$array["rlist"][0][0] = 'test1';
$array["rlist"][0][1] = 'test2';
$array["rlist"][0][2] = 'test3';
$array["rlist"][0][3] = 'test4';
$array["rlist"][0][4] = 'test5';

I get

Array ( 
    [0] => Array (
        [0] => test1
        [1] => test2 
        [2] => test3
        [3] => test4
        [4] => test5
    ) 
) 

What am I doing wrong?

CodePudding user response:

it's expected because the element is in

array[0][0]
array[1][0]
array[2][0]
array[3][0]
array[4][0]

so if you want to edit then:

$array["rlist"][0][0] = 'test1';
$array["rlist"][1][0] = 'test2';
$array["rlist"][2][0] = 'test3';
$array["rlist"][3][0] = 'test4';
$array["rlist"][4][0] = 'test5';

CodePudding user response:

If you format your original output, you would see the proper formatting you need...

Array (
    [0] => Array ( [0] => test1 )
    [1] => Array ( [0] => test2 )
    [2] => Array ( [0] => test3 )
    [3] => Array ( [0] => test4 )
    [4] => Array ( [0] => test5 )
)

You can achieve this by setting each item seprately...

$array = [];

$array['rlist'][][] = 'test1';
$array['rlist'][][] = 'test2';
...

or set them in 1 chunk...

$array = [];

$array['rlist'] = [
    ['test1'],
    ['test2'],
    ['test3'],
    ['test4'],
    ['test5']
];

CodePudding user response:

You have an array like this:

$array["rlist"] = 
    Array ( [0] => Array ( [0] => 'test1' ) ,
            [1] => Array ( [0] => 'test2' ) ,
            [2] => Array ( [0] => 'test3' ) ,
            [3] => Array ( [0] => 'test4' ) ,
            [4] => Array ( [0] => 'test5' ) 
    )

The key is [$i ] and the value is an array, so you can edit like this :

$array["rlist"][0][0] = 'test1';
$array["rlist"][1][0] = 'test2';
$array["rlist"][2][0] = 'test3';
$array["rlist"][3][0] = 'test4';
$array["rlist"][4][0] = 'test5';

CodePudding user response:

To avoid handwriting the 2d structure of single-element rows, you can hydrate a flat array with array_chunk() with 1 element per chunk.

Code: (Demo)

$tests = ['test1', 'test2', 'test3', 'test4', 'test5'];

var_export(
    array_chunk($tests, 1)
);

Although it is not clear why you need to edit your array.

  • Related