Search code examples
phparraysindexingassociative-array

PHP How to convert array json string to array?


How to convert JSON array string to array Example - this is array json string -

$params = [{"143":"166"},{"93":"49"}];

when using json_decode

$options1 = json_decode($params, true);

but it returns

[super_attribute1] => Array
        (
            [0] => Array
                (
                    [143] => 166
                )

            [1] => Array
                (
                    [93] => 49
                )

        )

but I need how can we convert in this format ?

super_attribute] => Array
        (
            [143] => 163
            [93] => 49
        )

Solution

  • A nester foreach can solve this for you

    <?php
    
    $data = [
        [ 143=>166 ],
        [ 93=>49 ]
    ];
    
    $return = [];
    foreach ($data as $d)
    {
        foreach ($d as $k=>$v) $return[$k] = $v;
        unset($v);
    } unset($d);
    
    var_dump($return); // array(2) { [143]=> int(166) [93]=> int(49) }