简体   繁体   中英

how to display 2 different array in single array using for loop

My output is :

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [no] => 316198
                    [name] => Uma
                )

            [1] => Array
                (
                    [0] => Array
                        (
                            [totavg] => 3.0403
                            [tot] => 20.2023
                            [id] => 27
                            [pid] => 710600
                            [adr] => local
                            [photo] => 123.png
                            [date] => 19930-01-06 05:40 AM
                        )

                )

        )

)

and i want to show like :

{
    "no": "316198",
    "name": "Uma",
    "totavg": "3.0403",
    "tot": "20.2023",
    "id": "27",
    "pid": "710600",
    "adr": "local",
    "photo": "123.png",
    "date": "19930-01-06 05:40 AM"
}

How can I do it?

Use array_walk_recursive() to flatten your array and then use json_encode() to create the JSON representation of the array:

$result = array();
array_walk_recursive($array, function($v) use (&$result) { $result[] = $v; });
echo json_encode($result, JSON_PRETTY_PRINT);

If you know the key names of the sub-arrays beforehand, you could use array_merge() as shown in other answers, but those solutions will fail if your array is nested one level deeper, or if the positions of the sub-arrays aren't known beforehand.

Output:

[
    316198,
    "Uma",
    3.0403,
    20.2023,
    27,
    710600,
    "local",
    "123.png",
    "19930-01-06 05:40 AM"
]

Demo

You could merge all array in one with

$resultArray = array();
foreach($bigArray as $array) {
    array_merge($resultArray, $array);
}
var_dump($resultArray);

array_merge() should work:

<?php

$new_array = array_merge($old_array[0][0], $old_array[0][1][0]);

echo '<pre>'.print_r($new_array, true).'</pre>';

// I see you want JSON format?
echo json_encode($new_array);

?>

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