0

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;
        }
1
  • The "full working solution" makes no sense with the original sample data. The first level keys will never equal cat_name. Commented Jun 25, 2024 at 11:05

2 Answers 2

5

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Just beat me! I avoided using a pointer, as it's just one more thing to understand if you don't already get it.
See my edit, I had to look up a value while looping. Perhaps that was the problem. Thanks again.
2

Assuming your array is in $a

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

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.