1

I have main array:

$data_cities = Array ( 

[0] => Array ( 
    [_type] => _items_city_sorting [item_city_sorting] => Moscow 
) 
[1] => Array (
    [_type] => _items_city_sorting [item_city_sorting] => Saint-Petersburg 
) 
[2] => Array ( 
    [_type] => _items_city_sorting [item_city_sorting] => Sochi 
) )

I want to make another array just like:

$cities = array (
[1] => 'Moscow',
[2] => 'Saint-Petersburg',
[3] => 'Sochi' )

The function that I use returns only the last value

  if ( $data_cities ) {
    foreach ( $data_cities as $key => $city ) {
      $cities[ $city->$key+1 ] = $city['item_city_sorting'];
    }
  }

Array ( [1] => Sochi ) 

What am I doing wrong? Thanks for the help=)

The main array was obtained using Carbon Fields if this is important

  • When looking at that duplicate, there are various methods which work for different versions of PHP, the latest way would be to use [array_column()](http://php.net/manual/en/function.array-column.php) – Nigel Ren Aug 14 '18 at 07:25
  • I do also, but in the final array, only the last value is returned) –  Aug 14 '18 at 07:38
  • Try changing `[ $city->$key+1 ]` to `[]` (also make sure you initialise the array before hand) – Nigel Ren Aug 14 '18 at 07:42

2 Answers2

0

As you want the number of the key+1 just use this term inside your foreach:

$cities[ $key+1 ] = $city['item_city_sorting'];
Marvin Fischer
  • 2,552
  • 3
  • 23
  • 34
0

You can try following inside your foreach:

$cities[] = $city['item_city_sorting'];
 or
array_push($cities,$city['item_city_sorting']);

Add the value dynamically into your city array

For example

if ( $data_cities ) {
 foreach ( $data_cities as $key => $city ) {
  $cities[] = $city['item_city_sorting'];
 }
}
Mahesh Hegde
  • 1,131
  • 10
  • 12