TheRealPapa
TheRealPapa

Reputation: 4539

Laravel 5.4 array remove key index

In my controller, this statement generates an array:

// sort the region collection by continent for faster access in front end
$finalRegions = $regions->sortBy('continent_id');


{  
   "0":{  
      "id":1,
      "name":"Alaska",
      "image_x":227,
      "image_y":117
   },
   "1":{  
      "id":5,
      "name":"Australian Antartic Territory",
      "image_x":1187,
      "image_y":1037
....
   }
}

How do I remove the index from the resulting object, so it looks like this:

[  
   {  
      "id":1,
      "name":"Alaska",
      "image_x":227,
      "image_y":117
   },
   {  
      "id":5,
      "name":"Australian Antartic Territory",
      "image_x":1187,
      "image_y":1037
....
   }
]

This is stored in a field cast as json in the table class.

Upvotes: 1

Views: 9870

Answers (3)

Jannie Theunissen
Jannie Theunissen

Reputation: 30154

Since you have "Laravel" in your question title and it looks like you already have your regions in a Laravel Collection, there is an easier way. Just pipe your results through ->values() after the ->sortBy() clause like this:

$finalRegions = $regions->sortBy('continent_id')->values();

Upvotes: 4

kawadhiya21
kawadhiya21

Reputation: 2528

$res = [];
foreach ($finalRegions  as $key => $value) {
    $res[] = $value;
}

// $res contains desired result

Edit: Simple one liner (thanks to Jannie)

$res = array_values($finalRegions)

Upvotes: 4

Viet Nguyen
Viet Nguyen

Reputation: 2373

I still don't get why you need to remove those indexes, but you can do by this way.

<?php

$jsonArr = '{  
   "0":{  
      "id":1,
      "name":"Alaska",
      "image_x":227,
      "image_y":117
   },
   "1":{  
      "id":5,
      "name":"Australian Antartic Territory",
      "image_x":1187,
      "image_y":1037
   }
}';

$decodeArr = json_decode($jsonArr, true);
print_r(json_encode($decodeArr));

This is just my idea, and you can edit part of your code where the query returns your JSON string.

Upvotes: 0

Related Questions