【问题标题】:PHP foreach loop to build multi arrayPHP foreach 循环构建多数组
【发布时间】:2011-08-30 11:10:36
【问题描述】:

我正在尝试用这种结构构建一个多数组:

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
                )
        )
)

我正在使用这个 foreach 循环,但我坚持将 cars 数组嵌入到 search data 数组中。

每个用户可能拥有不止一辆汽车,因此我需要遍历每个用户的所有汽车,生成该数组,并将其放入原始的 foreach 循环中。

    $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;

有什么建议吗?

感谢您的帮助!

样本表数据

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

【问题讨论】:

  • 应该 $row->car_id 已经是一个数组了吗?
  • 我只是把它放在那里以显示我需要帮助的地方 - 让它这样只会返回一辆汽车,而不是用户可能拥有的汽车阵列 - 我需要遍历所有汽车每个用户
  • 如果汽车被分隔在不同的行上,很难将其放入数组中,因为当您将其放入数组时,相同查询的下一个结果会浪费,您明白我的意思吗?

标签: php arrays loops multidimensional-array foreach


【解决方案1】:

您似乎正在通过数据库表创建数组。那么您能否提供2个或更多示例数据。如果有样本数据,回答会更容易。

编辑: 好吧,这可能不是最好的代码,但我认为您在看到此代码后将能够找到更好的方法

$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
    }

【讨论】:

  • 只需在 OP 中添加一些示例数据 - 让我知道您的想法,谢谢
  • @torr 这是我用这个解决方案得到的数组 Array ( [2] => Array ( [name] => Jack [location] => A [cars] => Array ( [0] => Porsche [1] => Toyota ) [5] => Array ( [name] => Luke [location] => B [cars] => Array ( [0] => Honda [1] => VW [ 2] => 玛莎拉蒂 ) ) [1] => 数组 ( [名称] => 贾巴 [位置] => C [汽车] => 数组 ( [0] => 特斯拉 ) ) )
  • 实际上,您使用 array_push 的想法非常适合这种情况 - 不确定其他解决方案是否比这更有效 - 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-30
  • 1970-01-01
  • 2011-08-30
  • 2011-06-09
  • 2020-05-17
相关资源
最近更新 更多