1 week ago

Parent child order is mismatch after array convert to json?

Posted 1 week ago by somenet77

I have a categories table with parent id and I have generated the parent-child select dropdown. But array return after database query is not ordered as array after convert to JSON.

array:5 [▼
  1 => "Deondre Little"
  2 => "-Prof. Hope Hettinger"
  4 => "-Axel Kirlin II"
  5 => "-Dr. Otha Schumm Sr."
  3 => "Roberto Kilback"

When a response to JSON is an output like below

    "1": "Deondre Little",
    "2": "-Prof. Hope Hettinger",
    "3": "Roberto Kilback",
    "4": "-Axel Kirlin II",
    "5": "-Dr. Otha Schumm Sr."

I need JSON key-value pair like an array key value.

However, I fix this issue on my way like this

public function listCategories()
        $newCategoriesList = [];

        $categories = $this->categoryContract->listCategories();

        foreach($categories as $key => $value) {
            $newCategoriesList[] = [
                'id' => $key,
                'name' => $value

        return $newCategoriesList;

Is a better way than i used ?

Please sign in or create an account to participate in this conversation.