major697
major697

Reputation: 1862

Add column name to array

I have this array:

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

I need insert multiple this values, I found this answer: How to insert multiple rows from a single query using eloquent/fluent, but I don't know how I can add column name to my array, to make it look like this:

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

I can't use array_map, because I have different values in the key: 1, 2, 3

Upvotes: 0

Views: 1394

Answers (1)

clem
clem

Reputation: 3366

An array key needs to be unique within an array. e.g. you can't have multiple keys called user_id within a single array. What you can do instead is have an array in the following format:

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

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

That's also what the answer you're linking to describes. The php code for the above array looks like this:

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

Upvotes: 2

Related Questions