Search code examples
phparrayslistjsonencode

PHP Array to List only values


Have an array as:

print_r($rowsiid);

Result:

Array ( [0] => Array ( [i_id] => 85 ) [1] => Array ( [i_id] => 94 ) [2] => Array ( [i_id] => 99 ) [3] => Array ( [i_id] => 101 ) [4] => Array ( [i_id] => 103 ) [5] => Array ( [i_id] => 105 ) [6] => Array ( [i_id] => 107 ) [7] => Array ( [i_id] => 109 ) [8] => Array ( [i_id] => 117 ) [9] => Array ( [i_id] => 119 ) )

Converting it to list as:

echo json_encode($rowsiid);

Result:

[{"i_id":85},{"i_id":94},{"i_id":99},{"i_id":101},{"i_id":103},{"i_id":105},{"i_id":107},{"i_id":109},{"i_id":117},{"i_id":119}]

But was expecting result as:

[85,94,99,101,103,105,107,109,117,119]


Solution

  • You've got an indexed array of associative arrays -- even though those associative arrays have only one element themselves. So each element in the outside array (e.g., $array[0]) is itself another array:

    print_r($array[0]);
    
    Array
    (
        [i_id] => 85
    )
    

    If you just want the i_id value from each element, you'll have to extract it specifically. You can do this pretty easily with array_column():

    print_r(array_column($array, 'i_id'));
    
    Array
    (
        [0] => 85
        [1] => 94
        [2] => 99
        [3] => 101
        [4] => 103
        [5] => 105
        [6] => 107
        [7] => 109
        [8] => 117
        [9] => 119
    )
    

    And then if you want a JSON string of that, just encode it:

    echo json_encode(array_column($array, 'i_id'));
    
    [85,94,99,101,103,105,107,109,117,119]