-3

我在 PHP 中有一种情况,我需要组合多个数组值并与第一个数组键绑定,假设我有以下数组,

[services] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 1
        )

    [package_type] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 1
        )

    [service_desc] => Array
        (
            [0] => Full HD
            [1] => Full HD
            [2] => Full HD
        )

    [service_price] => Array
        (
            [0] => 500
            [1] => 600
            [2] => 500
        )

现在,我想用服务类型键绑定所有数组,比如 services[0] 将具有 package_type[0]、service_desc[0] 和 service_price[0] 的值。目的是我可以通过其 ID 轻松识别所有与服务相关的值。任何人都可以建议吗?

4

1 回答 1

0

array_map是这里的关键。将第一个参数保留为 null,它将根据需要进行分组:

<?php

$data = 
[
    'services' =>
    [
        'programming',
        'debugging'
    ],
    'description' => 
    [
        'the process of writing computer programs.',
        'the process of identifying and removing errors from software/hardware'
    ]
];

$result = array_map(null, $data['services'], $data['description']);
var_export($result);

输出:

array (
  0 => 
  array (
    0 => 'programming',
    1 => 'the process of writing computer programs.',
  ),
  1 => 
  array (
    0 => 'debugging',
    1 => 'the process of identifying and removing errors from software/hardware',
  ),
)

您可以像这样解压缩,而不是将所有密钥作为参数写出:

array_map(null, ...array_values($data));

对于更详细的内容,请传递array_map一个可调用对象:

$keys   = array_keys($data);
$result = array_map(function(...$args) use ($keys) {
    return array_combine($keys, $args);
}, ...array_values($data));

var_export($result);

输出:

array (
  0 => 
  array (
    'services' => 'programming',
    'description' => 'the process of writing computer programs.',
  ),
  1 => 
  array (
    'services' => 'debugging',
    'description' => 'the process of identifying and removing errors from software/hardware',
  ),
)
于 2020-02-19T09:17:33.503 回答