0

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

2
  • You may use array sort by key Commented Sep 24, 2021 at 14:17
  • @A.ANoman ksort will make it categories, sku, title, user_id, I want it to be title, SKU, categories, user_id Thanks Commented Sep 24, 2021 at 14:21

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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']

    ));
}

2 Comments

Actually, I have a very large array with many more columns (the above one is just an example), but I do have a $columns keys array, I just want my array data to be arranged
@MZH, Ok fine. Please check your keys alphabetical orders. If keys are alphabetical then no need array_push but if you need custom key then you have no alternative

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.