tags:

views:

37

answers:

2

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
            [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;
        }
+4  A: 

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;
St. John Johnson
Just beat me! I avoided using a pointer, as it's just one more thing to understand if you don't already get it.
adam
stef
adam
See my edit, I had to look up a value while looping. Perhaps that was the problem. Thanks again.
stef
+2  A: 

Assuming your array is in $a

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