PHP array_values sorted by given indexes - php

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

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);
}

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

Insert multiple items in Laravel Collection inside a php loop

Hi I am trying to insert multiple items into a laravel collection inside a php loop but only one is getting inserted (the last one), please help to insert all the values.
This array $some_array = array(); has values like 1,2,3,4
The loop is like
foreach ($some_array as $key => $value) {
$final_lists = collect([
(object) [
'customer_id' => $value,
],
]);
}
Output required
"final_lists": [
{
"customer_id": 4,
"name": "Name 1",
},
{
"customer_id": 2,
"name": "Name 2",
},
]
use collection class at the top of the page.as,
use Illuminate\Support\Collection;
$collection = new Collection;
foreach([1,2,3,4] as $item) {
$collection->push((object)[
'customer_id' => $item,
'name' => 'demostring'.$item
]);
}
dd($collection->all());
use this snippet. Let me know the results.
If you require a list of multiple collections, you can append a new collection to an array like:
$a = [1,2,3,4,5]; // Your Array
$requiredList = [];
foreach($a as $key => $value){
$requiredList[] = (object)[
'customer_id' => $value,
'name' => 'Customer Name: ' . $value
];
}
dd($requiredList);
It will provide the desired list like:
^ array:5 [▼
0 => {#3971 ▼
+"customer_id": 1
+"name": "Name1"
}
1 => {#3207 ▼
+"customer_id": 2
+"name": "Name2"
}
2 => {#3977 ▼
+"customer_id": 3
+"name": "Name3"
}
3 => {#3961 ▼
+"customer_id": 4
+"name": "Name4"
}
4 => {#3956 ▼
+"customer_id": 5
+"name": "Name5"
}
]

How to make custom associative array using an array with foreach in php

I have an orders array. Now I want to group array elements according to their order_id. Then I did like below...
$CompleteOrders = [];
$OrderCount = 0;
foreach($OrdersWithProductDetails as $OrdersWithProductDetail) {
if(empty($CompleteOrders)) {
$CompleteOrders[$OrderCount][$OrderCount] = $OrdersWithProductDetail;
} else {
for($i = 0; $i < count($CompleteOrders); $i++) {
if(isset($CompleteOrders[$i][$i])) {
if($CompleteOrders[$i][$i]->order_id == $OrdersWithProductDetail->order_id) {
$CompleteOrders[$i][$OrderCount+1] = $OrdersWithProductDetail;
//print_r($CompleteOrders);
$OrderCount++;
} else {
$CompleteOrders[$OrderCount+1][0] = $OrdersWithProductDetail;
// print_r($CompleteOrders);
$OrderCount++;
}
}
}
// break;
}
}
dd($CompleteOrders);
But, when I print the $CompleteOrders array, in first element(0) there are all the order details which is belongs to order_id 93. but,
after that elements have different keys(3 and 4) even they has the same order_id like below.
array:3 [▼
0 => array:3 [▶]
3 => array:1 [▶]
4 => array:1 [▼
0 => {#1268 ▼
+"id": 102
+"size": "30"
+"order_quantity": "1"
+"price": "798"
+"created_at": "2020-06-16 19:24:00"
+"updated_at": "2020-06-16 19:24:00"
+"order_id": "94"
+"owi_id": "255"
+"item_id": "36"
+"item_name": "Acc One"
+"description": "Test"
+"quantity": null
+"main_fileimg": "1 (1).jpg"
+"main_filepath": "assets/img/product/accessories/"
+"main_category": "Accessories"
+"category": "Denim"
+"final_total_amount": "1593"
+"cus_name": "Customer Name"
+"tel_no": "123456789"
+"email": "email#gmail.com"
+"address_line_one": "Earth Rd"
+"address_line_two": "Neptune"
+"city": "Sun"
}
]
]
I want to create an array like below.
$Orders =
0 => [
0 => "OrderId94"
"Item"
1 => "OrderId94"
"Item"
],
1 => [
0 => "OrderId94"
"Item"
1 => "OrderId94"
"Item"
]
** EDIT **
$OrdersWithProductDetails = DB::table('order_id_with_owi_ids')
->join('orders_with_items','orders_with_items.id','order_id_with_owi_ids.owi_id')
->join('item_id_with_owi_ids','item_id_with_owi_ids.owi_id','orders_with_items.id')
->join('products','products.item_id','item_id_with_owi_ids.item_id')
->join('item_with_main_categories','item_with_main_categories.item_id','products.item_id')
->select('orders_with_items.*', 'order_id_with_owi_ids.*', 'products.*')
->get();
How can I do this?
It looks like you are overengineering
What about https://laravel.com/docs/7.x/collections#method-groupby
I think your OrdersWithProductDetails is a Laravel Collection you can use GroupBy to group them by the order_id
$grouped = $OrdersWithProductDetails->groupBy('order_id');
$grouped = $grouped->toArray();
dd($grouped);

how to get data to save from arrays inside array

i have form to make a bill for multiple products,
that form return request like this
#parameters: array:5 [▼
"quantity" => array:2 [▼
0 => "1"
1 => "2"
]
"product" => array:2 [▼
0 => "Mr. Jasen Beer,OliveDrab,XS"
1 => "Carlotta Yundt"
]
"date" => array:2 [▼
0 => "2019-12-29"
1 => "2019-12-29"
]
"id" => array:2 [▼
0 => "15"
1 => "11"
]
]
}
i need to loop all arrays to make insert all at once
thanks.
Try to loop it like this, you will get the array wrap every product's attributes:
$inserted_array = [];
foreach($parameters as $key => $values) {
foreach($values as $index => $val) {
$inserted_array[$index][$key] = $val;
}
}
\DB::table('table_name')->insert($inserted_array);
And I found that there is id in your array, remember to make it fillable.

Add key and value to array if it doesnt exist

So I have an Array called $sales that consits of objects like:
"DR22" => array:3 [▼
"brand" => "DR22"
"year" => "0"
"last_year" => null
]
"FGIPA46C" => array:3 [▼
"brand" => "FGIPA46C"
"month" => "3"
"year" => "3"
]
Now each one should have "Month" "Year" "Last Year" "Last Month" but if there is no sale its not in there, which i get, but if it doesnt exist I just want to add it with 0 value. I tried:
foreach ($sales as $sale)
{
if (empty($sale['month'])) {
$sale['month'] = 0;
}
}
But it doesnt add anything. Spits out the same.
foreach ($sales as &$sale) {if (empty($sale['month'])) { $sale['month'] = 0; }}
You need to pass the $sale array by reference (using the &). This will mean that the original $sales array is updated
Or you can use array_map function, for example:
$array = array_map(function($item){
if(empty($item["month"])){
$item["month"] = 0;
}
return $item;
}, $array);

Count the number of dinner invitations that are in array

I am using foreach loop that outputs an array
$dinnerDetails = array();
$lastDinnerDate = '';
$newDate = '';
foreach ($invitations as $invitation) {
$lastDinnerDate = $invitation['dinner_date'];
if ($invitation['dinner_date'] > $lastDinnerDate) {
$newDate = 'yes';
} else {
$newDate = 'no';
}
$dinnerDetails[] = array(
'request_id' => $invitation['request_id'],
'dinner_date' => $invitation['dinner_date'],
'dinner_id' => $invitation['dinner_id'],
'new_dinner' => $newDate
);
}
Output looks like this
array:4 [▼
0 => array:3 [▼
"request_id" => "48"
"dinner_id" => "36"
"dinner_date" => "2016-05-16T10:00:00"
"new_date" => "yes"
]
1 => array:3 [▼
"request_id" => "51"
"dinner_id" => "40"
"dinner_date" => "2016-05-16T10:00:00"
"new_date" => "no"
]
2 => array:3 [▼
"request_id" => "50"
"dinner_id" => "36"
"dinner_date" => "2016-05-27T10:00:00"
"new_date" => "yes"
]
3 => array:3 [▼
"request_id" => "52"
"dinner_id" => "41"
"dinner_date" => "2016-05-27T10:00:00"
"new_date" => "no"
]
]
My question is how can i count the number of times the dinner_id appeared. I would like to pass that value as part of the array because $dinnerDetails is being passed to the view so it will make it easier to display the count. The view already displays the data via foreach loop its only the count i need for each dinner_id
I assume you want to count the ID's and not the label / name itself, one ever so simple way would be doing it like so, simply place this inside of your foreach loop
$countDinner[$invitation['dinner_id']] = isset($countDinner[$invitation['dinner_id']]) ? $countDinner[$invitation['dinner_id']] + 1 : 1;
One coud also use a if clause instead of a ternary operator if one preffers, don't forget to place a
$countDinner = array();
Before the foreach loop to initialize the array, you should now have a array with the count of each dinner_id.
To add it to the existing array simply loop through as following:
foreach($dinnerDetails as &$dinnerDetail){
$dinnerDetail['count'] = $countDinner[$dinnerDetail['dinner_id']];
}
and the end result will look like this
0 => array:3 [▼
"request_id" => "48"
"dinner_id" => "36"
"dinner_date" => "2016-05-16T10:00:00"
"new_date" => "yes"
"count" => 2
]

Categories