1

I have a requirement to add an element to a PHP array. I would like to know whether I have to iterate over all the elements and add it OR do I have a shortcut to get this done?

[
  "A": ["id": 12, "name": "test1"],
  "B": ["id": 13, "name": "test2"]
]

I have to add "cut_id": 1 to each array and it should become:

[
  "A": ["id": 12, "name": "test1", "cut_id": 1],
  "B": ["id": 13, "name": "test2", "cut_id": 1]
]
1
  • I'd say you need to iterate. foreach() and array_push() should do the trick. Commented Jul 15, 2020 at 6:39

1 Answer 1

1

you can use data_fill helper funcation

    $data = [
        "A" => ["id" => 12, "name" => "test1"],
        "B" => ["id" => 13, "name" => "test2"]
    ];
    data_fill($data, '*.cut_id', 1);

    dd($data);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.