PHP将数组推入数组(保持顺序)[复制]

ddrv8njm  于 2022-12-21  发布在  PHP
关注(0)|答案(1)|浏览(159)

此问题在此处已有答案

Create an assoc array with equal keys and values from a regular array(3个答案)
昨天关门了。
有没有一种方法可以将一个现有的数组快速推入另一个数组?

$arr1 = [
        "entry1",
        "someEntry2",
        "someEntry3",
    ];

    $keys = [
        [
            "bla",
            "bla" => [
                "some other data"
            ]
        ],
        [
            "bla2",
            "bla2" => [
                "some other data"
            ]
        ],
        [
            "bla3",
            "bla3" => [
                "some other data"
            ]
        ],
    ];

最后,“final”数组应如下所示:

$final = [
        "entry1" => [
            "bla",
            "bla" => [
                "some other data"
            ]
        ],
        "someEntry2"    => [
            "bla2",
            "bla2" => [
                "some other data"
            ]
        ],
        "someEntry3"    => [
            "bla3",
            "bla3" => [
                "some other data"
            ]
        ],
    ];

是否已经有了一个内置函数或一个速记函数(可能通过使用回调)?

6ljaweal

6ljaweal1#

你可以试试这个:

$keys = [
    "entry1",
    "someEntry2",
    "someEntry3",
];

$array_values = [
    [
        "bla",
        "bla" => [
            "some other data"
        ]
    ],
    [
        "bla2",
        "bla2" => [
            "some other data"
        ]
    ],
    [
        "bla3",
        "bla3" => [
            "some other data"
        ]
    ],
];

$final = [];
foreach ($keys as $key) {
    foreach ($array_values as $value) {
        $final[$key] = $value;
    }
}

echo '<pre>'.print_r($final, true).'</pre>';

结果:

Array
(
    [entry1] => Array
        (
            [0] => bla3
            [bla3] => Array
                (
                    [0] => some other data
                )

        )

    [someEntry2] => Array
        (
            [0] => bla3
            [bla3] => Array
                (
                    [0] => some other data
                )

        )

    [someEntry3] => Array
        (
            [0] => bla3
            [bla3] => Array
                (
                    [0] => some other data
                )

        )

)

相关问题