如何将数组转换为多维数组并推送值

时间:2019-06-10 01:04:04

标签: php multidimensional-array

我有两个要加入的多重选择输入结果。关于送货目的地和送货费用。

这是我的数组结果:

Array
(
    [destination] => Array
        (
            [0] => London
            [1] => Liverpool
            [2] => Nottingham
            [3] => Oxford
        )

    [fee] => Array
        (
            [0] => 10
            [1] => 15
            [2] => 20
            [3] => 25
        )

)

我想将这些值推送到每个数组:

$ status =“ 1”;

我期望的结果是:

Array
(
    [0] => Array
        (
            [destination] => London
            [fee] => 10
            [status] => 1
        )
    [1] => Array
        (
            [destination] => Liverpool
            [fee] => 15
            [status] => 1
        )
    [2] => Array
        (
            [destination] => Nottingham
            [fee] => 20
            [status] => 1
        )
    [3] => Array
        (
            [destination] => Oxford
            [fee] => 25
            [status] => 1
        )

)

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

$array = ['destination' => ['London', 'Liverpool', 'Nottingham', 'Oxford'], 'fee' => [10, 15, 20, 25]];


$result = [];

foreach ($array['destination'] as $index => $value)
{
    $result[] = ['destination' => $value, 'fee' => $array['fee'][$index], 'status' => 1];
}

答案 1 :(得分:0)

尝试一下:https://3v4l.org/004PF

<?php

$givenArray = [
    'destination' => [
        'London',
        'Liverpool',
        'Nottingham',
        'Oxford',
    ],
    'fee' => [
        10,
        15,
        20,
        25
    ],
];


$output = [];
foreach ($givenArray['destination'] as $key => $destination) {
    $fee = $givenArray['fee'][$key];

    $output[] = [
        'destination' => $destination,
        'fee' => $fee,
        'status' => 1,
    ];
}

print_r($output);

输出为:

Array
(
    [0] => Array
        (
            [destination] => London
            [fee] => 10
            [status] => 1
        )

    [1] => Array
        (
            [destination] => Liverpool
            [fee] => 15
            [status] => 1
        )

    [2] => Array
        (
            [destination] => Nottingham
            [fee] => 20
            [status] => 1
        )

    [3] => Array
        (
            [destination] => Oxford
            [fee] => 25
            [status] => 1
        )

)