简体   繁体   中英

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

I'm trying to figure out how to build the "desired" array from my "current" array.

My current array is an indexed array, but each value is actually two values separated by a |. I currently explode() each array value to produce two separate values. I'd like to convert the current array to a two-dimensional array where the 1st array is indexed and the nested array is an associative array.

I've tried several ideas, but none work. Any help to convert it programmatically is greatly appreciated.

My "Current" Array

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

My "Desired" array

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

Something like this will work:

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

Output:

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

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