Home > other >  json_decode creates unnecessary arrays
json_decode creates unnecessary arrays

Time:02-10

I got this JSON which I need to convert to associative PHP array

[
    {
        "32": {
            "name": "Price File Jan 2022.xlsx",
            "datastartingrow": "1"
        }
    },
    {
        "33": {
            "name": "Price File Feb 2022.xlsx",
            "datastartingrow": "2"
        }
    }
]

$decoded = json_decode($json, true) creates unnecessary arrays [0] and [1], so I can't access $decoded[32] without double looping.

Array
(
    [0] => Array
        (
            [32] => Array
                (
                    [name] => Price File Jan 2022.xlsx
                    [datastartingrow] => 1
                )

        )

    [1] => Array
        (
            [33] => Array
                (
                    [name] => Price File Feb 2022.xlsx
                    [datastartingrow] => 2
                )

        )

)

Is there an elegant way of accessing each array by using key [32] and [33]?

Thanks.

CodePudding user response:

Somthing like this should be appropriate for a start

<?php
$data = '{"32":{"name":"Price File Jan 2022.xlsx","datastartingrow":"1"},"33":{"name":"Price File Feb 2022.xlsx","datastartingrow":"2"}}';

$decoded = json_decode($data, true);

foreach($decoded as $key => $element){
  echo 'element key is '.$key.' and item is '. json_encode($element). ' |||||||||||||||||| ' ;
}

?>

Check out the live example here

CodePudding user response:

$jsonStr = '[
    {
        "32": {
            "name": "Price File Jan 2022.xlsx",
            "datastartingrow": "1"
        }
    },
    {
        "33": {
            "name": "Price File Feb 2022.xlsx",
            "datastartingrow": "2"
        }
    }
]';
$decoded = json_decode($jsonStr,true);

Direct access to the array with key 32:

$a32 = array_column($decoded,32)[0];
/*
array (
  'name' => "Price File Jan 2022.xlsx",
  'datastartingrow' => "1",
)
*/

Similarly for key 33

$a33 = array_column($decoded,33)[0];
  •  Tags:  
  • Related