0

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")
);
Mr. B
  • 2,677
  • 6
  • 32
  • 42
  • Related: [Access and explode comma-delimited data from multidimensional array then populate a new 2d array](https://stackoverflow.com/q/23490898/2943403) – mickmackusa Jan 15 '23 at 06:29

1 Answers1

1

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

Nick
  • 138,499
  • 22
  • 57
  • 95
  • I update your demo to look more like the one that OP desires: https://3v4l.org/eSKs3 – catcon Sep 30 '19 at 01:07
  • 1
    @catcon I was asleep at the wheel. You should post that as an answer. – Nick Sep 30 '19 at 01:09
  • @Nick Thanks for your help! Can you explain why you use `$apps[]` instead of `$apps()`? Also, if I try to `var_dump($apps[]);` I get the following error, "Fatal error: Cannot use [] for reading in". Any ideas why? Thanks again! – Mr. B Sep 30 '19 at 03:56
  • 1
    @Mr.B the `$arr[] = value` notation is shorthand for `array_push($arr, value)`; it is an easy way to add a value to the end of an array. Since that's what it means, you can't use it in an expression, so you need to just `var_dump($apps);` – Nick Sep 30 '19 at 03:58