简体   繁体   中英

How to convert multidimentional key value into single array?

I have the following array:

{
        "image": "/b/l/black_10.jpg"
    },
    {
        "url_key": "printing-products"
    },
    {
        "position_back": "251,252"
    },
}

I need all the above array into a single array as below.

{
        "image": "/b/l/black_10.jpg"

        "url_key": "printing-products"

        "position_back": "251,252"

}

I need to convert it as a single array. I used the below code.

$flat = call_user_func_array('array_merge', $attr_code);

But I couldn't achieve expected output.

it's look like json data. But not valid.

First make in valid. you can test on https://jsonlint.com/

After that using json_decode convert into array.

You can use array_walk_recursive to convert multidimensional key value into single array.

   <?php
//Using json_decode convert json into array
$array = json_decode($json, true);

array_walk_recursive($array, function($item, $key) use (&$final_array){$final_array[$key]=$item;});


/*use json_encode for json format
   echo json_encode($final_array);
 */

//For array you can use $final_array
echo "<pre>";
print_r($final_array);

?>

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM