Is there an alternative for array_merge? - php

The problem is, I'm not getting the expected results of my array code.
I've tried doing the array_merge, but all it does was to merge all the arrays.
$medicine_order = $request['medicine_id'];
array:3 [▼
0 => "25"
1 => "32"
2 => "30"
]
$medicine_quantity = $request['medicine_quantity'];
array:3 [▼
0 => "3"
1 => "10"
2 => "6"
]
$count = 0;
foreach ($medicine_order as $id) {
$item = new Historyitem;
$item->medicine_id = $id;
foreach ($medicine_quantity as $id2) {
$item->historyitem_quantity = $id2;
}
$item->save();
$count++;
}
I wanted to store these values in my DB.
array:3 [▼
0 => "25"
1 => "3"
]
array:3 [▼
0 => "32"
1 => "10"
]
array:3 [▼
0 => "30"
1 => "6"
]
but instead I get these values:
array:3 [▼
0 => "25"
1 => "6"
]
array:3 [▼
0 => "32"
1 => "6"
]
array:3 [▼
0 => "30"
1 => "6"
]

Solution is change your foreach loop to this:
$count = 0;
foreach ($medicine_order as $key=>$id) {
$item = new Historyitem;
$item->medicine_id = $id;
$item->historyitem_quantity = $medicine_quantity[$key];
$item->save();
$count++;
}
Reason why you are getting wrong result is, your internal foreach loop, it iterates over every element of your $medicine_quantity array and every time it replaces the older value with new value, hence you are getting the value of last index i.e., "6" in final result.

You need to process the $medicine_quantity values in the same order as the $medicine_order values, which you can do by matching the keys to each array. Try this instead:
foreach ($medicine_order as $key => $id) {
$item = new Historyitem;
$item->medicine_id = $id;
$item->historyitem_quantity = $medicine_quantity[$key];
$item->save();
$count++;
}

Related

How can I sum values of an array with the same key sorted by category?

category:
array:3 [▼
"78f895684c" => "blue"
"f71db561ba" => "green"
"3e231651de" => "blue"
]
numbersGroup:
array:3 [▼
0 => array:4 [▼
"uuid" => "78f895684c"
"price" => "10"
"discount" => "0"
"total" => "10.00"
]
1 => array:4 [▼
"uuid" => "f71db561ba"
"price" => "2"
"discount" => "0"
"total" => "2.00"
]
2 => array:4 [▼
"uuid" => "3e231651de"
"price" => "50"
"discount" => "10"
"total" => "40.00"
]
]
I try to create an array that sorts my items into categories, but also sums all items in a category together. This is what I have:
foreach ($numbersGroup as $group) {
$cat = $category[$group['uuid']];
unset($group['uuid']);
$numbersArray[$cat][] = $group;
}
With the result:
array:2 [▼
"blue" => array:2 [▼
0 => array:3 [▼
"price" => "10"
"discount" => "0"
"total" => "10.00"
]
1 => array:3 [▼
"price" => "50"
"discount" => "10"
"total" => "40.00"
]
]
"green" => array:1 [▼
0 => array:3 [▼
"price" => "2"
"discount" => "0"
"total" => "2.00"
]
]
]
This is what I am trying to achieve:
array:2 [▼
"blue" => array:2 [▼
0 => array:3 [▼
"price" => "60"
"discount" => "10"
"total" => "50.00"
]
]
"green" => array:1 [▼
0 => array:3 [▼
"price" => "2"
"discount" => "0"
"total" => "2.00"
]
]
]
This is my approach:
foreach ($numbersGroup as $group) {
$cat = $category[$group['uuid']];
unset($group['uuid']);
foreach ($group as $key => $value) {
$sum += $value;
}
$numbersArray[$cat][] = $sum;
}
But I get the error:
Unsupported operand types
Check if $numbersArray[$cat] is already set - if so, don’t add a new array element, but add the individual values to the existing array keys.
foreach ($numbersGroup as $group) {
$cat = $category[$group['uuid']];
unset($group['uuid']);
if(isset($numbersArray[$cat])) {
$numbersArray[$cat]['price'] += $group['price'];
$numbersArray[$cat]['discount'] += $group['discount'];
$numbersArray[$cat]['total'] += $group['total'];
}
else {
$numbersArray[$cat] = $group; // no [] here, because we want only a single element
}
}
Or, without an explicit if, using the ?? operator instead:
foreach ($numbersGroup as $group) {
$cat = $category[$group['uuid']];
$numbersArray[$cat]['price'] = ($numbersArray[$cat]['price'] ?? 0) + $group['price'];
$numbersArray[$cat]['discount'] = ($numbersArray[$cat]['discount'] ?? 0) + $group['discount'];
$numbersArray[$cat]['total'] = ($numbersArray[$cat]['total'] ?? 0) + $group['total'];
}
--
Edit:
I unfortunately I cannot write into my code "price", "discount" etc, because these values are always different, this cannot be hardcoded
Then loop over the keys you get from group, as you tried to with your initial code already:
foreach ($numbersGroup as $group) {
$cat = $category[$group['uuid']];
unset($group['uuid']);
foreach($group as $key => $value) {
$numbersArray[$cat][$key] = ($numbersArray[$cat][$key] ?? 0) + $value;
}
}
Can you try the below code
foreach ($numbersGroup as $group) {
$cat = $category[$group['uuid']];
if(!isset( $numbersArray[$cat][0]) )
$numbersArray[$cat][] = $group;
else{
// If index is known, you can use below code
/*$numbersArray[$cat][0]["price"]+= $group['price'];
$numbersArray[$cat][0]["discount"]+= $group['discount'];
$numbersArray[$cat][0]["total"]+= $group['total'];*/
// If index is not known
foreach($group as $key => $value){
if (is_numeric($value)) {
$numbersArray[$cat][0][$key]+= $group[$key];
}
}
}
}
Now I have added the case if array index is not known. We need a numeric checking before adding the values.
I hope this helps you :)

Looping a Multi Dimensional Array

I encountered this kind of array in my tasks. It's a multi dimensional array.
In the form, I have this,
particular[particular][]
particular[percentage][]
particular[remarks][]
So what I'm doing is, I'm getting request
$inputs = $request->all();
this returns
array:3 [▼
"particular" => array:3 [▶]
"percentage" => array:3 [▶]
"remarks" => array:3 [▶]
]
inside, each of them have
array:3 [▼
"particular" => array:3 [▼
0 => "11"
1 => "22"
2 => "33"
]
"percentage" => array:3 [▼
0 => "11"
1 => "22"
2 => "33"
]
"remarks" => array:3 [▼
0 => "na1"
1 => "na2"
2 => "na3"
]
]
I tried looping it
foreach ($inputs as $input) {
dd($input);
}
but I only get the first one "particular" => array:3 [▶]
What I'm after is, I need to save those value in database
$particular = new Particular;
$particular->particular = particular;
$particular->percentage = percentage;
$particular->remarks = remarks;
$particular->save();
dd means "dump and DIE" so your script dies on first iteration.
You can:
$particular = new Particular;
$particular->particular = $inputs['particular'];
$particular->percentage = $inputs['percentage'];
$particular->remarks = $inputs['remarks'];
$particular->save();
Also, if you need to just dump something - there's a dump function (surprise!):
foreach ($inputs as $input) {
dump($input);
}
I managed to find a solution. I don't know if this is the proper, but for now atleast it work for me.
$array1 = $request->particular;
$array2 = $request->percentage;
$array3 = $request->remarks;
$merge = [$array1, $array2, $array3];
foreach ($merge[0] as $key => $value) {
$particular = new Particular;
$particular->particular = $merge[0][$key];
foreach ($merge[1] as $x => $y) {
$particular->percentage = $merge[1][$key];
}
foreach ($merge[2] as $i => $d) {
$particular->remarks = $merge[2][$key];
}
$particular->report_id = $report->id;
$particular->save();
}

PHP array structure change

This shouldn't be confusing me as much as it is but I am looking to turn this:
array:3 [▼
"subject" => array:2 [▼
0 => "math"
1 => "english"
]
"grade" => array:2 [▼
0 => "a"
1 => "b"
]
"received" => array:2 [▼
0 => "2017"
1 => "2016"
]
]
into this:
array:2 [▼
"0" => array:3 [▼
"subject" => "math"
"grade" => "a"
"received" => "2017"
]
"1" => array:3 [▼
"subject" => "english"
"grade" => "b"
"received" => "2016"
]
]
Tried looping through in a couple different ways but never seem to get the result I am looking for, any help would be much appreciated!
$keys = array_keys($array);
$result = array_map(
function (...$values) use ($keys) { return array_combine($keys, $values); },
...array_values($array)
);
Which is essentially this, but less repetitive:
array_map(
function ($subject, $grade, $received) {
return [
'subject' => $subject,
'grade' => $grade,
'received' => $received
];
},
$array['subject'],
$array['grade'],
$array['received']
)
See the manual for array_map and ... for more explanation.
simple Version:
$arr1 = array(...);
$arr2 = array();
foreach ($arr1 as $k => $v) {
foreach ($v as $x => $y) {
$arr2[$x][$k] = $y;
}
}
But you should add conditions, if the array element not exists, create it, or you may get Errors, depending on your PHP configuration.

How to select arrays in multidimensional array with a value in php

To put it right lets say I have an array stores-
array:3 [▼
0 => "store3"
1 => "store"
2 => "store2"
]
This is the array which holds values.
Other array products holds all the data:-
array:2 [▼
0 => array:2 [▼
"store" => "store"
"product" => "1"
]
1 => array:2 [▼
"store" => "store"
"product" => "4"
]
2 => array:2 [▼
"store" => "store2"
"product" => "2"
]
3 => array:2 [▼
"store" => "store2"
"product" => "3"
]
4 => array:2 [▼
"store" => "store3"
"product" => "7"
]
5 => array:2 [▼
"store" => "store3"
"product" => "11"
]
]
What I want is that a value is picked from stores array eg store3 then it is compared with products array and being searched and extract all the arrays inside products array which has the store value store3 and store it in another new array named store3
I have tried to do it but it was very wrong I mean it didn't work! I will post it if anyone say so but can anyone accomplish this?
My work:-
$temp = array();
for($i=0; $i<count($stores); $i++)
{
//$stores[$i] = array();
foreach($products as $p)
{
if(session($stores[$i]) == $p['store'])
{
if(count(session($stores[$i])) == 0)
{
$temp['product'] = $p['product'];
session($stores[$i])->push($temp['product']);
}
else if(!in_array($p['product'],$stores[$i]))
{
$temp['product'] = $p['product'];
session($stores[$i])->push($temp['product']);
}
}
}
}
Do it like below:-
$final_array = array();
foreach($array1 as $arr){
foreach($array2 as $arr2){
if($arr == $arr2['store']){
$final_array[$arr]['product'][] = $arr2['product'];
}
}
}
echo "<pre/>";print_r($final_array);
Output:-https://eval.in/752498
using array_walk
$array = [];
array_walk($products, function ($value, $key) use ($stores, &$array) {
$array[$value['store']][] = $value['product'];
});
live sample : https://3v4l.org/BfeMm
using array filter
$store = 'store1';
$products = array_filter($products, function($product) use($store) {
return (isset($product['store']) and $product['store'] == $store);
});
var_dump($products);
https://eval.in/752508
I made a simple function to find products in store
function searchProduct($products,$storeName){
$results =array();
foreach($products as $product){
if(in_array($storeName,array_values($product)))
$results[] = $product;
}
return $results;
}
print_r(searchProduct($products,'store3'));

How to sum 2 multidimensional arrays that can have different sizes?

I have two multi dim arrasy, that I need to get the sum of them.
Arrays:
array:5 [▼
0 => {#275 ▼
+"pharmacy_name": "CVS"
+"num": "6"
+"reversed": "2"
}
1 => {#279 ▼
+"pharmacy_name": "KROGER"
+"num": "8"
+"reversed": "4"
}
2 => {#283 ▼
+"pharmacy_name": "PUBLIX"
+"num": "11"
+"reversed": "3"
}
3 => {#284 ▼
+"pharmacy_name": "RITE AID"
+"num": "0"
+"reversed": "2"
}
4 => {#286 ▼
+"pharmacy_name": "WALMART"
+"num": "13"
+"reversed": "5"
}
]
array:4 [▼
0 => {#288 ▼
+"pharmacy_name": "CVS"
+"num": "422"
+"reversed": "243"
}
1 => {#289 ▼
+"pharmacy_name": "RITE AID"
+"num": "0"
+"reversed": "1"
}
2 => {#290 ▼
+"pharmacy_name": "WALGREENS"
+"num": "209"
+"reversed": "99"
}
3 => {#291 ▼
+"pharmacy_name": "WALMART"
+"num": "6"
+"reversed": "3"
}
]
I wrote some code(as you will see next), but the problem I have is that the arrays are now allwasy equal, as in some pharmacy_name can be in first array, but not in second, and vice versa(KROGER is in fist array, but not in second, so the result does not have KROGER). The code so far:
$total = [];
foreach ($query as $key => $value) {
foreach ($queryOV as $k => $val) {
if(!isset($total[$value->pharmacy_name])){
$total[$value->pharmacy_name]['num'] =$value->num;
$total[$value->pharmacy_name]['reversed'] =$value->reversed;
}
if($value->pharmacy_name==$val->pharmacy_name){
$total[$value->pharmacy_name]['num'] += $val->num;
$total[$value->pharmacy_name]['reversed'] += $val->reversed;
}
}
}
Summs the rest, but missed the KROGER.Please help, thanks!
$total = [];
foreach (array_merge($a1, a2) as $x) {
if (!array_key_exists($x->pharmacy_name, $total))
$total[$x->pharmacy_name] = ['pharmacy_name' => $x->pharmacy_name, 'num'=> 0, 'reversed' => 0];
$total[$x->pharmacy_name]['num'] += $x->num;
$total[$x->pharmacy_name]['reversed'] += $x->reversed
}

Categories