Erdss4
Erdss4

Reputation: 1125

Convert single array into multidimensional array in PHP?

If I have this array in PHP:

array(3) {
  [0]=>
  string(5) "first"
  [1]=>
  string(6) "second"
  [2]=>
  string(5) "third"
}

How can I convert this single array into a multidimensional array? What is the quickest way? So I can access this array like:

$array["first"]["second"]...

I want to be able to then set a value to this index like:

$array["first"]["second"]["third"] = "example";

I thought that I need a for loop or a recursive function but I have no idea how to start.

Upvotes: 0

Views: 597

Answers (1)

ADyson
ADyson

Reputation: 61904

It wasn't quite as simple as I had imagined to begin with. The key to it was doing the process backwards - starting with the last array and then wrapping it in more arrays until you get back to the top level.

$array = array("first", "second", "third");
$newArr = array();

//loop backwards from the last element
for ($i = count($array)-1; $i >= 0 ; $i--)
{
    $arr = array();
    if ($i == count($array)-1) {
        $val = "example";
        $arr[$array[$i]] = $val;
    }
    else { 
        $arr[$array[$i]] = $newArr;
    }
    $newArr = $arr;
}

var_dump($newArr);
echo "-------".PHP_EOL;
echo $newArr["first"]["second"]["third"];

Demo: http://sandbox.onlinephpfunctions.com/code/0d7fa30fde7126160fbcc0e80e5727f17b19e39f

Upvotes: 1

Related Questions