在 php 中将索引数组转换为二维数组的最佳方法

Best way to convert an indexed array to a two-dimensional array in php

我正在尝试找出如何从我的 "current" 数组构建 "desired" 数组。

我当前的数组是一个索引数组,但每个值实际上是由|分隔的两个值。我目前对每个数组值进行 explode() 以生成两个单独的值。我想将当前数组转换为二维数组,其中第一个数组被索引并且嵌套数组是一个关联数组。

我尝试了几个想法,但 none 行得通。非常感谢任何以编程方式转换它的帮助。

我的"Current"数组

$appInfo = array("idNum1|dir/path1","idNum2|dir/path2","idNum3|dir/path3");

我的"Desired"数组

$apps = array(
  array("appID" => "$someVarAppID","appDir" => "$someVarAppPath"),
  array("appID" => "$someVarAppID","appDir" => "$someVarAppPath"),
  array("appID" => "$someVarAppID","appDir" => "$someVarAppPath"),
  array("appID" => "$someVarAppID","appDir" => "$someVarAppPath")
);

像这样的东西会起作用:

$apps = array();
foreach ($appInfo as $app) {
    list($id, $path) = explode('|', $app);
    $apps[] = array('appId' => $id, 'appDir' => $path);
}

输出:

Array
(
    [0] => Array
        (
            [appId] => idNum1
            [appDir] => dir/path1
        )
    [1] => Array
        (
            [appId] => idNum2
            [appDir] => dir/path2
        )
    [2] => Array
        (
            [appId] => idNum3
            [appDir] => dir/path3
        )
)

Demo on 3v4l.org