0

I have an array in laravel named $destinations and the values are:

    Collection {#391 ▼
      #items: array:2 [▼
        "Chicago, Illinois" => Collection {#398 ▼
          #items: array:10 [▶]
        }
        "New York City, New York" => Collection {#403 ▼
          #items: array:10 [▶]
        }
      ]
    }

This array is grouped by city name just like Chicago and New York, now I want to add one array item after the city name, it should be like this:

Collection {#391 ▼
  #items: array:2 [▼
    "Chicago, Illinois" => Collection {#398 ▼
      #items: array:10 [▶]
    "days" => "2"
    }
    "New York City, New York" => Collection {#403 ▼
      #items: array:10 [▶]
    "days" => "7"
    }
  ]
}

I'm trying to use array_merge when i loop the array, I use foreach($destinations as $key => $destination) in the looping, basically the $key will return increment number like 0, 1, 2, etc but in this case it return the city name. Anyone knows how to do it? or how to make the $key still increment number after grouped by in laravel?

0

1 Answer 1

1

As I see your $destinations variable is a collection. So you can iterate through it using each method.

for example:

$destinations = $destinations->each(function ($item, $key) {
    // You can modify $item here
    // $item['days'] = <no_of_days>;
});

To get the increment number, you can do something like this:

$element_position = 0;
$destinations = $destinations->each(function ($item, $key) use ($element_position) {
        // You can modify $item here
        // $item['days'] = <no_of_days>;
        // You can get the $element_position here
        // Iterate $element_position
        $element_position++;
});
Sign up to request clarification or add additional context in comments.

5 Comments

it works, but still I can't get the key number increment, is there any way to get the $key index number? because right now the $key contain the city name
the $item['days'] value should be the $key index number, so it is like 0, 1, 2. not the city names
Answer updated. Check if it fulfills your requirement.
The $element_position not incremented, still zero in each looping
I read here stackoverflow.com/questions/42773475/… and I add & in each function like this each(function ($item, $key) use (&$element_position) and now it works like a charm

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.