首页 > 解决方案 > Add one more element to array in loop with PHP

问题描述

I have array like below:

$arr=[["id"=>"001","name"=>"Hello","pict"=>"hello.jpg"],["id"=>"002","name"=>"Abc","pict"=>"abc.jpg"]];

i want to add one more element to array $arr by "link"=>"uploads/hello.jpg" My expected result:

$arr=[["id"=>"001","name"=>"Hello","pict"=>"hello.jpg","link"=>"uploads/hello.jpg"],["id"=>"002","name"=>"Abc","pict"=>"abc.jpg","link"=>"uploads/abc.jpg"]];

Any solution for this thank.

标签: php

解决方案


You can iterate over the array using foreach, passing a reference into the loop to allow the values to be modified directly:

$arr=[["id"=>"001","name"=>"Hello","pict"=>"hello.jpg"],["id"=>"002","name"=>"Abc","pict"=>"abc.jpg"]];

foreach ($arr as &$a) {
    $a['link'] = 'uploads/' . $a['pict'];
}

print_r($arr);

Output:

Array
(
    [0] => Array
        (
            [id] => 001
            [name] => Hello
            [pict] => hello.jpg
            [link] => uploads/hello.jpg
        )
    [1] => Array
        (
            [id] => 002
            [name] => Abc
            [pict] => abc.jpg
            [link] => uploads/abc.jpg
        )
)

Demo on 3v4l.org


推荐阅读