Home > database >  PHP array_values sorted by given indexes
PHP array_values sorted by given indexes

Time:09-25

Data is in this format, a list on an unarranged object array.

array:4 [▼
  0 => {#688 ▼
     "title": "My Item 1"
     "categories": "3,4,5,6"
     "sku": "1"
     "user_id": "5"
  }
  1 => {#663 ▼
     "title": "My Item 1"
     "sku": "2"
     "categories": "3,4,5,6"
     "user_id": "6"
  }
  2 => {#686 ▼
     "title": "My Item 1"
     "user_id": "7"
     "categories": "3,4,5,6"
     "sku": "3"
  }
  3 => & {#290 ▼
     "title": "My Item 1"
     "categories": "3,4,5,6"
     "sku": "4"
     "user_id": "8"
  }
]

but I want the values in an arranged array format like title, SKU, categories, user_id ("My Item 1", "2,3,5,6", "1", "5")

Right now I'm using array_values, but data comes in an unsorted way such as index 1 SKU is before the categories, how can I get it? is there some native PHP or Laravel method that we can use?

Edit: The above one is just an example array, the real data has 50 columns, so I can't define them statically in a loop.

Thanks

CodePudding user response:

If you just want to sort the keys, you could use ksort(), if you want them in specific order you could restructure the array like:

$arr = [...your array];
$newArr = [];

foreach ($arr as $item) {
    $newItem = [
        'title' => $item['title'],
        'SKU' => $item['SKU'],
        'categories' => $item['categories'],
        'user_id' => $item['user_id']
    ];

    array_push($newArr, $newItem);
}

CodePudding user response:

You have to use array_push if you want to custom array index like below

$expectedArray = array();

foreach ($your_array as $data){

    array_push($expectedArray ,array(

        'title'        => $data['title'],
        'SKU'          => $data['SKU'],
        'categories'   => $data['categories'],
        'user_id'      => $data['user_id']

    ));
}
  • Related