开发者

PHP foreach loop to build multi array

I'm trying to build a multi array with this structure:

Array
(
    [2] => Array //this is the user's unique ID
        (
            [name] => Jack
            [location] => Somerville, Massachusetts, United States
            [cars] => Array
                (
                    [10] => Toyota //this is the car's unique ID
                    [11] => Porsche
                )
        )

    [5] => Array
        (
            [name] => Luke
            [location] => Schwelm, North Rhine-Westphalia, Germany
            [cars] => Array
                (
                    [1] => Honda
                    [2] => VW
                    [5] => Maserati
                )
        )

    [1] => Array
        (
            [name] => Jabba
            [location] => Denver, Colorado, United States
            [cars] => Array
                (
                    [3] => Tesla
                )
        )
)

I am using this foreach loop but am stuck in getting the cars array embedded within the search data array.

Each user may have more t开发者_如何学Gohan one car so I would need to loop through all cars for each user, generate that array, and put it in the original foreach loop.

    $search_data = array();
    foreach ($query->result() as $row) {
        $search_data[$row->id] = array(

            'name' => $row->name,
            'location' => $row->location,
            'cars' => array($row->car_id), //this is where I need to insert another array
        );
    }
    return $search_data;

Any suggestions how to do this?

Thanks for helping!

SAMPLE TABLE DATA

USER    NAME    LOCATION    CARS
2       JACK    A           TOYOTA
2       JACK    A           PORSCHE
5       LUKE    B           HONDA
5       LUKE    B           VW 
5       LUKE    B           MASERATI
1       JABBA   C           TESLA


It seems that you are creating the array through a database table. So can you please give 2 or more sample data. it'll be easier to give an answer if sample data is there.

Edit: Well this might not be the best code but I think you'll be able to figure out a better way after seeing this

$id = $row['id'];
    if (!isset($search_data[$id])){
        $search_data[$id] = array();
    }
    $search_data[$id]['name'] = $row['name'];
    $search_data[$id]['location'] = $row['location'];
    if (isset($search_data[$id]['cars'])) {
        array_push($search_data[$id]['cars'],$row['cars']);
    }else{
        $search_data[$id]['cars'] = array($row['cars']); //this is where I need to insert another array
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜