add associative arrays with different keys to main associative array - php

Have problem with associative array.
I have code:
$array[]=[$key=>['value'=>$value,'value1'=>$value1'];
$key value can be repeated, it means that for $key = 4 we can have few options of $value and $value1.
It generates structure as following:
[0]=>[4=>['value'=>$value,'value1'=>$value1'];
[1]=>[4=>['value'=>$value,'value1'=>$value1'];
[2]=>[4=>['value'=>$value,'value1'=>$value1'];
The think is that i want to achieve different structure:
[4]=>[0=>['value'=>$value,'value1'=>$value1'];
[1 =>['value'=>$value,'value1'=>$value1'];
[2 =>['value'=>$value,'value1'=>$value1'];
laravel dd should show it that way:
^ array:1 [▼
4 => array:1 [▼
0 => array:2 [▶]
1 => array:2 [▶]
2 => array:2 [▶]
]
]
Inside array with key 4 i want to put few arrays with keys as following 0,1,2 etc.
I tried like so:
$array[$key]=[['value'=>$value,'value1'=>$value1']];
but its overriding inside array key, and any time its = 0 like here:
[4]=>[0=>['value'=>$value,'value1'=>$value1'];
laravel:
array:1 [▼
4 => array:1 [▼
0 => array:2 [▶]
]
]

What a shame just after post I get an idea.
$array[$key][]=['value'=>$value,'value1'=>$value1'];
That what I was looking for.

Related

How do I add new item with key to collection in Laravel?

I have a Laravel collection $Data. When I code outputs
dd($Data); // it outputs the following
Illuminate\Support\Collection {#1344 ▼
#items: array:3 [▼
0 => {#1342 ▶}
1 => {#1334 ▶}
2 => {#1346 ▶}
]
}
$Data->push(['Total'=>600]);
dd($Data);
When I push a Total, it does inserts but output is not as expected.
Illuminate\Support\Collection {#1344 ▼
#items: array:4 [▼
0 => {#1342 ▶}
1 => {#1334 ▶}
2 => {#1346 ▶}
3 => array:1 [▼
"Total" => 600
]
]
}
How do I get 3 => {#1353▶) ?
You're pushing an Array to $Data, while the other items in that Collection are Objects (stdClass or similar). To make this consistent, use casting:
$Data->push((object)['Total' => 600]);
Now you should see 3 => {#...} instead of 3 => array:1.

PHP - adding to multi dimensional array adds new arrays to the first array element rather than the correct element

I have a 'parent' array that I'm reading and based on some values I read in a child array of that parent I create a new child array. i.e. I sum the number of 'products' in the child array to create a new child array.
The new child array is being created correctly BUT rather than create the new child array in the corresponding parent array element, my logic is placing all of the new child arrays in the first element of the parent. Please help.
foreach ($orders as $order) {
$orderResource = new OrderResource(Order::findOrFail($order['id']));
$ordersAll[] = $orderResource;
foreach (($orderResource['products']) as $product) {
if (array_key_exists($product['productType'],$product_array)) {
// array_push($product_array, $product['productType']);
$product_array[$product['productType']] += (int)$product['quantity'];
}
else $product_array[$product['productType']] = (int)$product['quantity'];
}
$ordersAll['product'][]= $product_array;
$product_array=[];
}
Result: rather than a new 'product' array being in each array element they're all in index 0.
array:22 [▼
0 => array:9 [▶]
"product" => array:21 [▶]
1 => array:9 [▶]
2 => array:9 [▶]
3 => array:9 [▶]
4 => array:9 [▶]
5 => array:9 [▶]
6 => array:9 [▶]
7 => array:9 [▶]
8 => array:9 [▶]
9 => array:9 [▶]
10 => array:9 [▶]
11 => array:9 [▶]
12 => array:9 [▶]
13 => array:9 [▶]
14 => array:9 [▶]
15 => array:9 [▶]
16 => array:9 [▶]
17 => array:9 [▶]
18 => array:9 [▶]
19 => array:9 [▶]
20 => array:9 [▶]
]
So, what I'd like is to have each array index to contain a new 'product_sum' array. This will contain key values for all the Product types found and a sum of the 'quantity'.
current:
0 => array:9 [▼
"refId" => "8e24cc331a73002b0c2da4bc7a62c647"
"Currency" => "USD"
"Symbol" => "$"
"Amount" => "315.50"
"created_at" => "2020-12-08T03:32:09.000000Z"
"updated_at" => "2020-12-08T03:32:09.000000Z"
"legs" => array:2 [▶]
"travellers" => array:3 [▶]
"products" => array:3 [▼
0 => array:13 [▶]
1 => array:13 [▶]
2 => array:13 [▶]
]
]
what I'm after is (in each parent array index):
0 => array:9 [▼
"refId" => "8e24cc331a73002b0c2da4bc7a62c647"
"Currency" => "USD"
"Symbol" => "$"
"Amount" => "315.50"
"created_at" => "2020-12-08T03:32:09.000000Z"
"updated_at" => "2020-12-08T03:32:09.000000Z"
"legs" => array:2 [▶]
"travellers" => array:3 [▶]
"products" => array:3 [▼
0 => array:13 [▶]
1 => array:13 [▶]
2 => array:13 [▶]
"product_sum" => array:1 [▼
0 => array:2 [▼
"ticket" => 5
"bag" => 1
This line is forcing all the product arrays into the element named product of $ordersAll:
$ordersAll['product'][]= $product_array;
Not sure why you are interacting with a Resource this way but you can just reorder this to remove the problem with knowing the current index for $ordersAll:
foreach ($orders as $order) {
$orderResource = new OrderResource(Order::findOrFail($order['id']));
$product_array = [];
foreach ($orderResource['products'] as $product) {
if (array_key_exists($product['productType'], $product_array)) {
$product_array[$product['productType']] += (int)$product['quantity'];
} else {
$product_array[$product['productType']] = (int)$product['quantity'];
}
}
// TODO:
// need the code to add $product_array to $orderResource
$ordersAll[] = $orderResource;
}
Though you should be able to build this list from a couple Collection methods and no need of looping anything yourself:
Order::findOrFail(...)->products->groupBy('productType')->map->sum('quantity');
I beleive this is the issue
$ordersAll[] = $orderResource;
...
$ordersAll['product'][]= $product_array;
You are adding the order to the ordersAll array, but then adding and overwriting the same product key each time.

PHP Get a specific property from an array of objects with different array count

I am in a confusing situation right now.
So, I have an array of objects
array:3 [▼
0 => array:5 [▶]
1 => array:2 [▶]
2 => array:10 [▶]
]
Each array items contains another array which will have objects
array:3 [▼
0 => array:5 [▼
0 => {#215 ▼
+"DefaultTimeLength": 40
+"ProgramID": 4
+"NumDeducted": 1
+"ID": 245
+"Name": "30-Swedish-Massage"
}
1 => {#216 ▼
+"DefaultTimeLength": 70
+"ProgramID": 4
+"NumDeducted": 1
+"ID": 246
+"Name": "60-Swedish-Massage"
}
2 => {#217 ▶}
3 => {#218 ▶}
4 => {#219 ▶}
]
1 => array:2 [▶]
2 => array:10 [▶]
]
What I want to achieve is, I want to get the 'ID' and 'Name' as an array for every array of objects from this array. Since, every array inside the main array have different counts, I cannot use a FOR loop, to get the required data.
Any ideas?
use nested foreach loop e.g:
foreach($main as $m){
foreach($m as $item){
echo $item->ID ." ".$item->Name;
}
}
use 2 foreach loop inside eachother
foreach ($array as $item) {
foreach ($item as $sub) {
echo $sub['ID'] . " " . $sub['Name'] . "<br>";
}
}
your full code will be something like this

Merge 2 arrays by their index in each row [duplicate]

This question already has answers here:
PHP's array_merge_recursive behaviour on integer keys
(5 answers)
Closed 5 months ago.
I have 2 arrays, each will always have the same number of rows and same number of values per row.
I need to merge the 2 arrays together, to combine the results on each row, but in a particular way (there will always be only 3 results per row on each array too):
For example, for each row, take the first result of each array, and put them next to each other, then the second result of each array, and put them next to each other, then finally the third.
So Array 1's value will always precede Array 2's value (example shown below):
Array 1:
array:7 [▼
24 => array:3 [▼
0 => 0
1 => 0.66666666666667
2 => 0.66666666666667
]
25 => array:3 [▶]
26 => array:3 [▶]
27 => array:3 [▶]
29 => array:3 [▶]
30 => array:3 [▶]
31 => array:3 [▶]
]
Array 2:
array:7 [▼
24 => array:3 [▼
0 => 0.375
1 => 0.42857142857143
2 => 0.55555555555556
]
25 => array:3 [▶]
26 => array:3 [▶]
27 => array:3 [▶]
29 => array:3 [▶]
30 => array:3 [▶]
31 => array:3 [▶]
]
Intended Combined Array Format:
array:7 [▼
24 => array:6 [▼
0 => 0
1 => 0.375
2 => 0.66666666666667
3 => 0.42857142857143
4 => 0.66666666666667
5 => 0.55555555555556
]
25 => array:6 [▶] ...
Current loop which returns the incorrect layout:
$results = array();
foreach ($questionDetails as $key => $question) {
for ($i = 0; $i < 3; $i++) {
$results[$key][] = $array1[$key] + $array2[$key];
}
}
Returns:
array:7 [▼
24 => array:3 [▼
0 => array:3 [▼
0 => 0
1 => 0.66666666666667
2 => 0.66666666666667
]
1 => array:3 [▼
0 => 0
1 => 0.66666666666667
2 => 0.66666666666667
]
2 => array:3 [▼
0 => 0
1 => 0.66666666666667
2 => 0.66666666666667
]
]
25 => array:3 [▶]
26 => array:3 [▶]
27 => array:3 [▶]
29 => array:3 [▶]
30 => array:3 [▶]
31 => array:3 [▶]
]
I'm unsure why my loop isn't just adding the three values from each row together - but then I think they still won't be in the right order, but I'm unsure of how to approach this.
Many thanks.
This is the "unfancy" (but save) solution if I understand your question correctly - all keys are preserved an set as desired:
$array1;
$array2;
$results = array();
foreach ($questionDetails as $key => $question1) {
$question2 = $array2[$key];
$tp = array();
$tp[0] = $question1[0];
$tp[1] = $question2[0];
$tp[2] = $question1[1];
$tp[3] = $question2[1];
$tp[4] = $question1[2];
$tp[5] = $question2[2];
$results[$key] = $tp;
}
EDIT: There is a way more flexible way to implement this where the number of arguments may vary (see PHP: array_merge() in alternate order (zip order)?).
$array1;
$array2;
function array_zip(...$arrays) {
return array_merge(...array_map(null, ...$arrays));
}
$results = array();
foreach ($questionDetails as $key => $question1) {
$results[$key] = array_zip($question1,$array2[$key]);
}
I would do this:
$combined = array();
foreach($array1 as $key => $value){
$combined[$key] = array();
foreach($value as $key2 => $value2){
$combined[$key][] = $value2;
$combined[$key][] = $array2[$key][$key2];
}
}
For a variable number of records.

PHP- Array combine not working properly

I am trying to do array combine, but it is not working properly. I have one array called $models which consits of objects and it looks like this:
array:5 [▼
0 => Comment {#377 ▶}
1 => Thumb {#378 ▶}
2 => View {#379 ▶}
3 => Vote {#380 ▶}
]
Then since I am passing it to another function, I am adding one more object as an element like this:
array_push($models, new User);
And then I get an array that looks like this:
array:5 [▼
0 => Comment {#377 ▶}
1 => Thumb {#378 ▶}
2 => View {#379 ▶}
3 => Vote {#380 ▶}
4 => User {#399 ▶}
]
I am then doing foreach loop to get the total count in the DB for each model like this:
foreach ($models as $model){
$modelCounts[] = $model->count();
}
My $modelCounts than looks like this:
array:5 [▼
0 => 19
1 => 22
2 => 15
3 => 17
4 => 3
]
And then I am trying to do array_combine so that my objects are keys and the counts are values like this:
$result = array_combine($models, $modelCounts);
But something is not working right because when I do dd($result); I get:
array:1 [▼
"[]" => 3
]
But when I do it the other way around like this:
$result = array_combine($modelCounts, $models);
It works fine and I get:
array:5 [▼
19 => Comment {#377 ▶}
22 => Thumb {#378 ▶}
15 => View {#379 ▶}
17 => Vote {#380 ▶}
3 => User {#399 ▶}
]
But I need it the other way around and not like this.
Objects can't be used as key for associative arrays, only scalar values are allowed.
http://php.net/manual/en/language.types.array.php
Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.
The reason why the first array_combine() fails is that an objcect cannot be usead as an array key.
You may want to create an array containing classes names first by using get_class() to get class's name and then combine it with $modelCounts
It should look something like this
foreach ($models as $model){
$modelNames[] = get_class($model);
}
$result = array_combine($modelNames, $modelCounts);

Categories