0

It works fine creating level-1, but when level-2 is being created, it only updates the first letter of index [1].

Code:

// Position [Level-1]
$taxonomy_id = [
  "id_no_1",
  "id_no_2",
  "id_no_3",
];

// Position [Level-2]
$titles = [
  "title_1",
  "title_2",
  "title_3",
];

$array = [];


for ($i = 0; $i < count($taxonomy_id); $i++) {

//Construct level-1
$array[] = $taxonomy_id["{$i}"];

//Construct level-2
$array["{$i}"]["{$i}"] = $titles["{$i}"];

}

print_r($array);

Result:

(
    [0] => td_no_1
    [1] => it_no_2
    [2] => id_no_3
)

Wanted result:

Array
(
    [id_no_1] => Array
        (
            [0] => title_1
        )

    [id_no_2] => Array
        (
            [0] => title_2
        )

)

1 Answer 1

1

You would be better off creating the sub arrays in one go, you can also simplify "{$i}" with $i...

for ($i = 0; $i < count($taxonomy_id); $i++) {
    $array[$taxonomy_id[$i]] = [$titles[$i]];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Would it be possible to add 2 sub-levels using the same for loop? I intended to add a separate question but my question quota for the day is breached.

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.