开发者

Adding an element to a multidimensional array

开发者 https://www.devze.com 2022-12-23 14:58 出处:网络
How can I loop through the array below and an element per array, with key \"url_slug\" and value \"foo\"? I tried with array_push but that gets rid of the key names (it seems?) Doing a foreach($array

How can I loop through the array below and an element per array, with key "url_slug" and value "foo"? I tried with array_push but that gets rid of the key names (it seems?) Doing a foreach($array as $k => $v) doesn't do it either, I think.

The new array should be exactly the same only having 4 elements per array instead of 3, with the key / values above.

Array
(
    [0] => Array
        (
            [name_en] => Test 5
            [url_name_nl] => test-5
    开发者_Go百科        [cat_name] => mobile
        )

    [1] => Array
        (
            [name_en] => Test 10
            [url_name_nl] => test-10
            [cat_name] => mobile
        )

    [2] => Array
        (
            [name_en] => Test 25
            [url_name_nl] => test-25
            [cat_name] => mobile
        )

)

EDIT: full working solution. A little more complex than originally described

foreach ($prods as $key => &$value)
        {
            if($key == "cat_name") $slug = $value['cat_name'];          
            $url_slug = $this->lang->line($slug);       
            $value['url_slug'] = $url_slug;
        }


You need to modify the value in the foreach. Use the & in the foreach.

Try this:

 foreach ($array as $key => &$value)
   $value['url_slug'] = $url_slug;


Assuming your array is in $a

foreach($a AS $key=>$value) {
    $a[$key]['url_slug'] = 'foo';
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号