简体   繁体   中英

Building multidimensional array with input from 2 arrays

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
        )

)

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]];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM