将列名添加到数组

时间:2017-10-07 12:59:27

标签: php arrays

我有这个数组:

[
    [
        "302260",
        "302250",
        "302248",
    ],
    [
        "Bruce Willis",
        "Jackie Chan",
        "Gary Oldman",
    ],
]

我需要插入多个这个值,我找到了这个答案:How to insert multiple rows from a single query using eloquent/fluent,但我不知道如何将列名添加到我的数组中,使它看起来像这样:

[
    [
        "user_id" => "302260",
        "user_id" => "302250",
        "user_id" => "302248",
    ],
    [
        "name" => "Bruce Willis",
        "name" => "Jackie Chan",
        "name" => "Gary Oldman",
    ]
]

我无法使用array_map,因为我在密钥中有不同的值:1, 2, 3

1 个答案:

答案 0 :(得分:2)

数组键在数组中必须是唯一的。例如你不能在一个数组中有多个名为user_id的键。您可以做的是使用以下格式的数组:

Array
(
    [1] => Array
        (
            [user_id] => 1
            [name] => User1
        )

    [2] => Array
        (
            [user_id] => 2
            [name] => User2
        )
)

这也是你所链接的答案所描述的内容。 上面数组的php代码如下所示:

$users = array(
  1 => array("user_id" => 1, "name" => "User1"),
  2 => array("user_id" => 2, "name" => "User2"),
);