x2p
x2p

Reputation: 27

Building a multidimensional Array with another Array in PHP

I try to build an array. I don't wanna write something like $array[3][5][8] = []. Because the count of the first Array can change, here it's 3 but it also can be like 9 or 12. Also the values can change, but they are always unique numbers. I hope someone knows a better way. Thank you.

// First Array, which I have. The count and the content can change.
array(3) {
  [0]=>
  string(1) "3"
  [1]=>
  string(1) "5"
  [2]=>
  string(1) "8"
}

// Second Array, thats the goal.
array(1) {
  [3]=>
  array(1) {
    [5]=>
    array(1) {
      [8]=>
      array(0) {
      }
    }
  }
}

Upvotes: 2

Views: 864

Answers (3)

    $array1=array(3,5,8);
    $array2=array();
    for($i=count($array1);$i>0;$i--){
        $temp=array();
        $temp[$array1[$i-1]]=$array2;
        $array2=$temp;
    }

Upvotes: 1

krasipenkov
krasipenkov

Reputation: 2029

This code will solve your problem:

$array = [3,5,8,9]; // your first array 

$newArray = null;
foreach ($array as $value) {
    if($newArray === null) {
        $newArray[$value] = [];
        $ref = &$newArray[$value];
    }
    else {
        $ref[$value] = [];
        $ref = &$ref[$value];
    }
}

$newArray - holds the result you wanted

Upvotes: 2

SOFe
SOFe

Reputation: 8214

  • $subject is the reference to the array you are currently in.
  • $array is the main root array that you obtain in the end.
  • $input is the input int array.

    $subject = $array = [];
    foreach($input as $key){
      $subject[$key] = []; // create empty array
      $subject =& $subject[$key]; // set reference to child
      // Now $subject is the innermost array.
      // Editing $subject will change the most nested value in $array
    }

Upvotes: 0

Related Questions