Home > Mobile >  JSON into PHP array
JSON into PHP array

Time:03-12

I want to convert a multilevel JSON file into a PHP array but it doesn't work and I don't know how to do it anymore. I want to get the value of the quantity width the id value.

Here my JSON

[
    {
        "id": 2114,
        "stocks": [
            {
                "quantity": 0,
                "minHandlingDays": 1,
                "maxHandlingDays": 2
            }
        ],
        "sku": "B1005122"
    },
    {
        "id": 2115,
        "stocks": [
            {
                "quantity": 0,
                "minHandlingDays": 1,
                "maxHandlingDays": 2
            }
        ],
        "sku": "B1005123"
    },
    {
        "id": 2139,
        "stocks": [
            {
                "quantity": 0,
                "minHandlingDays": 1,
                "maxHandlingDays": 2
            }
        ],
        "sku": "B1020141"
    },
    {
        "id": 2141,
        "stocks": [
            {
                "quantity": 0,
                "minHandlingDays": 1,
                "maxHandlingDays": 2
            }
        ],
        "sku": "B1020139"
    }
]

And here my newest but filed try:

$array = json_decode($json, true);
    for($i = 0; $i <= count($array); $i  ){
        $json2 = $array[$i]['stocks'];
        $array2 = json_decode(strval($json2));
        print_r($array2);
    }

CodePudding user response:

You can just use

$array = json_decode($json, true);

CodePudding user response:

The json_decode function converts the entire json string into an array, even a multidimensional one. Therefore, it is enough to use this function once.

Try it like this

$array = json_decode($json, true);
foreach($array as $value){ 
    // with foreach
    foreach($value['stocks'] as $stock){
        print_r($stock['quantity']);
    }
    // or
    print_r($value['stocks'][0]['quantity']);
}

 
  • Related