2

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) {
      }
    }
  }
}
2
  • $count = count($given); if ($count === 3) { $new[$given[0]][$given[1]][$given[2]] = []; } I did this. And it works, but for that I have to create for each case ($count) a really bad code. Commented Nov 3, 2016 at 9:05
  • True. You need to loop over your first array. This way it doesn't matter how many elements it has. Commented Nov 3, 2016 at 9:08

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Flaggers / reviewers: For code-only answers such as this one, downvote, don't delete!
0
  • $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
    }

1 Comment

Thank you. I think I did something wrong. Result is array(0) {}; I replaced the $input with my given array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.