如何在php中的数组元素中添加数组

问题描述 投票:0回答:1

如何在数组元素中添加数组?

before: ["1","4","2"]

after: [
       "1"["one","two"],
       "4"["five","eight"],
       "2"["nine","ten"]
       ]

我想在现有数组的每个元素中添加值数组。

php arrays json multidimensional-array
1个回答
0
投票

因为我们不知道

"one" and "two"
的东西来自哪里,所以你必须逐行执行而不是循环执行

$before = ['1', '4', '2'];

$after[$before[0]] = ['one', 'two']; 
$after[$before[1]] = ['four', 'five']; 
$after[$before[2]] = ['seven', 'nine']; 
print_r($after);

结果

Array
(
    [1] => Array
        (
            [0] => one
            [1] => two
        )

    [4] => Array
        (
            [0] => four
            [1] => five
        )

    [2] => Array
        (
            [0] => seven
            [1] => nine
        )

)
© www.soinside.com 2019 - 2024. All rights reserved.