How to parsing data - php

my response to request in my laravel aplication is:
Array
(
[0] => Array
(
[order_product_id] => 39
[ean] => 1255AA
[quantity] => 1
)
[1] => Array
(
[order_product_id] => 40
[ean] => 1326489131511
[quantity] => 1
)
)
How to parsing this data in my aplication?
I tried to:
foreach ($request->all() as $data)
{
print_r($data['ean']);
die();
}
I get this error: Undefined index: ean
Edit: When I use var_export($request->all()) I get:
array (
'Array
(
____' =>
array (
0 => '> Array
(
[order_product_id] => 39
[ean] => 1255AA
[quantity] => 1
)
[1] => Array
(
[order_product_id] => 40
[ean] => 1326489131511
[quantity] => 1
)
)',
),
)
Thank you very much.

It seems like $request->all() returns data as something like that:
$array = [
'Array ( ____' => [
[
'order_product_id' => 39,
'order_id' => 34,
'product_id' => 48,
'name' => 'iPod Classic',
'model' => 'product 20',
'ean' => '1255AA',
'quantity' => '1',
'price' => 10.0000,
'total' => 10.0000,
'tax' => 0.0000,
'reward' => 0
],
]
];
So, instaed of:
foreach ($request->all() as $data)
use:
foreach (array_shift($request->all()) as $data)

Related

Get total sum of repeating IDs stored in multidimensional array

I have a multidimensional array of items added to cart in codeigniter. Lets say I order food for me and several friends (specific IDs stored in next level array). Now in case someone has more items I need to get total sum of each friend and save it as money owned to me. How to loop all items to get total sum of each friend with same ID (I cannot move the friend ID to parent array). I store them to database in a way we can see in the table below in non-repeating way. I need a new array to get results like this(to store/update them).
friend_id
amount_owned
52
35
28
5
friend_id 0 is me...we skip me != 0
Array
(
[array] => Array
(
[carthashid1] => Array
(
[0] => Array
(
[foodid] => 322
[price] => 5
[name] => Chicken Burger
[options] => Array
(
[friend_id] => 52
[special_instructions] =>
)
[rowid] => ceec8698316fe95ec9d7dccf961f32c1
[num_added] => 5
[sum_price] => 25
)
[1] => Array
(
[foodid] => 323
[price] => 5
[name] => Beef Burger
[options] => Array
(
[friend_id] => 52
[special_instructions] =>
)
[rowid] => c2d1c15d159123d1cbdce967785ef06e
[num_added] => 2
[sum_price] => 10
)
[2] => Array
(
[foodid] => 322
[price] => 5
[name] => Chicken Burger
[options] => Array
(
[friend_id] => 28
[special_instructions] =>
)
[rowid] => 3daa7b14b23a5c0afa9b196ea6e35227
[num_added] => 1
[sum_price] => 5
)
[3] => Array
(
[foodid] => 323
[price] => 5
[name] => Beef Burger
[options] => Array
(
[friend_id] => 0
[special_instructions] =>
)
[rowid] => 734c9cc82cf35e2dcc42f28d96a8ebde
[num_added] => 1
[sum_price] => 5
)
)
)
[finalSum] => 45
[finalItemsCount] => 9
)
It would have taken me less time to check my answer if I didnt have to Hand Code the array, but here it is anyway
$input = [
'array' => [
'carthashid1' => [
[
'foodid' => 322, 'price' => 5,
'name' => 'Chicken Burger',
'options' => ['friend_id' => 52, 'special_instructions' => ''],
'rowid' => 'ceec8698316fe95ec9d7dccf961f32c1', 'num_added' => 5,'sum_price' => 25
],
[
'foodid' => 322, 'price' => 5,
'name' => 'Beef Burger',
'options' => ['friend_id' => 52,'special_instructions' => ''],
'rowid' => 'ceec8698316fe95ec9d7dccf961f32c1', 'num_added' => 2,'sum_price' => 10
],
[
'foodid' => 322,'price' => 5,'name' => 'Chicken Burger',
'options' => ['friend_id' => 28,'special_instructions' => ''],
'rowid' => 'ceec8698316fe95ec9d7dccf961f32c1', 'num_added' => 1,'sum_price' => 5
],
[
'foodid' => 322, 'price' => 5, 'name' => 'Beef Burger',
'options' => ['friend_id' => 0,'special_instructions' => ''],
'rowid' => 'ceec8698316fe95ec9d7dccf961f32c1', 'num_added' => 1, 'sum_price' => 5
]
]
]
];
$friends = [];
foreach($input['array']['carthashid1'] as $ordered){
if ($ordered['options']['friend_id'] == 0) {
// its me, ignore me
continue;
}
if ( ! isset($friends[$ordered['options']['friend_id']]) ) {
// initialise the accumulator for this friend
$friends[$ordered['options']['friend_id']] = 0;
}
$friends[$ordered['options']['friend_id']] += $ordered['sum_price'];
}
print_r($friends);
RESULT
Array
(
[52] => 35
[28] => 5
)
You could theoretically do entire task in single DB query, also the friend_id can be moved to parent array by modifying DB query.
Slightly different approach to keep friend_id, amount_owned structure:
$owned = [];
foreach($arr['array']['carthashid1'] as $item){
if(isset($item['options']['friend_id']) && $item['options']['friend_id'] != 0)
{
if(count($owned) && ($key = array_search($item['options']['friend_id'], array_column($owned, 'friend_id'))) !== false){
// we found friend id in array lets add the price:
$owned[$key]['amount_owned'] += $item['sum_price'];
continue;
}
// when we dont find the friend id in array create that item here:
$owned[] = ['friend_id' => $item['options']['friend_id'], 'amount_owned' => $item['sum_price']];
}
}
print_r($owned);
Result:
Array
(
[0] => Array
(
[friend_id] => 52
[amount_owned] => 35
)
[1] => Array
(
[friend_id] => 28
[amount_owned] => 5
)
)

sum value in foreach loop based on another value php

I have an array like below. There are id, label, cost, and cid in an array. We want to sum the cost based on the cid like for cid 22 cost should be 196.5 and for cid 11 cost should be 44.4. In our out put array we want to keep the label, cost (sum), and cid, Please see expected output array.
Array
(
[0] => Array
(
[id] => 1331
[label] => PM1
[cost] => 98.25
[cid] => 22
[product_id] => 133
)
[1] => Array
(
[id] => 1332
[label] => PM3
[cost] => 22.20
[cid] => 11
[product_id] => 133
)
[2] => Array
(
[id] => 1341
[label] => PM1
[cost] => 98.25
[cid] => 22
[product_id] => 134
)
[3] => Array
(
[id] => 1342
[label] => PM3
[cost] => 22.20
[cid] => 11
[product_id] => 134
)
)
Tried below
foreach ($array $key => $value) {
$final[$value['cid']] += $value['cost'];
}
print_r ($final);
Getting below as an output
Array
(
[22] => 196.5
[11] => 44.4
)
Want expected output like below.
Array
(
[22] => Array
(
[label] => PM1
[cost] => 196.5
[cid] => 22
)
[11] => Array
(
[label] => PM3
[cost] => 44.4
[cid] => 11
)
)
Basically want to sum cost based on cid and want to keep the label, cost (sum), and cid.
Any help will be greatly appreciated.
I believe this should do the trick
$CIDs_identified = array();
$final_array = array();
foreach($original_array as $small_array){
if(!in_array($small_array['cid'], $CIDs_identified)){
$CIDs_identified[] = $small_array['cid'];
$final_array[$small_array['cid']] = array(
'label' => $small_array['label'],
'cost' => $small_array['cost'],
'cid' => $small_array['cid'],
);
}else{
$final_array[$small_array['cid']]['cost'] += $small_array['cost'];
}
}
On this site, if you can provide your source array in usable format, that is really helpful so that we don't have to retype it. One way to do that is using var_export.
Below is a simple version. Create an array indexed by cid. If that item doesn't exist, populate it with the basic data and a zero cost. Then on each loop, including the initial, add the row's cost.
<?php
$data = [
[
'id' => 1331,
'label' => 'PMI',
'cost' => 98.25,
'cid' => 22,
'product_id' => 133,
],
[
'id' => 1341,
'label' => 'PMI',
'cost' => 98.25,
'cid' => 22,
'product_id' => 134,
],
];
$output = [];
foreach ($data as $item) {
if (!isset($output[$item['cid']])) {
$output[$item['cid']] = [
'label' => $item['label'],
'cost' => 0,
'cid' => $item['cid'],
];
}
$output[$item['cid']]['cost'] += $item['cost'];
}
print_r($output);
Demo here: https://3v4l.org/MY6Xu
$list = [
[ 'id' => 1331, 'label' => 'PM1', 'cost' => 98.25, 'cid' => 22, 'product_id' => 133 ],
[ 'id' => 1332, 'label' => 'PM3', 'cost' => 22.20, 'cid' => 11, 'product_id' => 133 ],
[ 'id' => 1341, 'label' => 'PM1', 'cost' => 98.25, 'cid' => 22, 'product_id' => 134 ],
[ 'id' => 1342, 'label' => 'PM3', 'cost' => 22.20, 'cid' => 11, 'product_id' => 134 ]
];
$result = [];
array_walk($list, function ($item) use (&$result) {
if (isset($result[$item['cid']])) {
$result[$item['cid']]['cost'] = $item['cost'] + $result[$item['cid']]['cost'];
} else {
$result[$item['cid']] = [ 'label' => $item['label'], 'cost' => $item['cost'], 'cid' => $item['cid'] ];
}
});
print_r($result);
Output:
Array
(
[22] => Array
(
[label] => PM1
[cost] => 196.5
[cid] => 22
)
[11] => Array
(
[label] => PM3
[cost] => 44.4
[cid] => 11
)
)

PHP - Merge 2 multidimensional array based on value

Currently, I have 2 multidimensional array and I'm looking to combine them into one giant array where the value's name in array 1 matches the value's name in array 2.
The array's look as followed...
Array1
(
[0] => Array
(
[id] => 1
[name] => test1
[desc] => test_desc
[quantity] => 3
)
[1] => Array
(
[id] => 2
[name] => test2
[desc] => test_desc
[quantity] => 33
)
)
Array2
(
[0] => Array
(
[holder] => 'John'
[name] => test1
[desc] => test_desc
[location] => ATL
)
[1] => Array
(
[holder] => 'Jackie'
[name] => test3
[desc] => test_desc
[location] => SF
)
)
I'm looking to merge the arrays where the 'name' column in array1 matches in array2 and also combine the columns in array's 1 & 2 into the final array. This should look like...
FinalArray
(
[0] => Array
(
[id] => 1
[holder] => 'John'
[name] => test1
[desc] => test_desc
[location] => ATL
[quantity] => 3
)
[1] => Array
(
[holder] => 'Jackie'
[name] => test3
[desc] => test_desc
[location] => SF
)
[2] => Array
(
[id] => 2
[name] => test2
[desc] => test_desc
[quantity] => 33
)
)
Where the "test1" combines the different columns across the 2 arrays into a new array inside the "FinalArray". I've tried researching some ideas with array_merge and array_merge_recursive but I'm not entirely sure if I'm going in the correct direction. Thanks in advance.
Try like this
$array1=[['id' => 1,'name' => 'test1','desc' => 'test_desc','quantity' => 3],
['id' => 2,'name' => 'test2','desc' => 'test_desc','quantity' => 33]];
$array2=[['holder' => 'John','name' => 'test1','desc' => 'test_desc','location' => 'ATL'],
['holder' => 'Jackie','name' => 'test3','desc' => 'test_desc','location' => 'SF']];
$final=[];
foreach ($array1 as $key1=>$data1){
foreach ($array2 as $key2=>$data2){
if($data1['name']==$data2['name']){
$final[]=$data1+$data2;
unset($array1[$key1]);
unset($array2[$key2]);
}
}
}
if(!empty($array1)){
foreach ($array1 as $value){
$final[]=$value;
}
}
if(!empty($array2)){
foreach ($array2 as $value){
$final[]=$value;
}
}
It will give output as
One more solution
function merge_by_name(array $arr1, array $arr2) {
$result = [];
foreach ($arr1 as $value) {
$key = array_search($value['name'], array_column($arr2, 'name'));
if($key !== false) {
$result[] = array_merge($value, $arr2[$key]);
unset($arr2[$key]);
} else {
$result[] = $value;
}
}
$result = array_merge($result, $arr2);
return $result;
}
Test
$arr1 = [
[
'id' => 1,
'name' => 'test1',
'desc' => 'test_desc',
'quantity' => 3
],
[
'id' => 2,
'name' => 'test2',
'desc' => 'test_desc',
'quantity' => 33
],
];
$arr2 = [
[
'holder' => 'John',
'name' => 'test1',
'desc' => 'test_desc',
'location' => 'ATL'
],
[
'holder' => 'Jackie',
'name' => 'test3',
'desc' => 'test_desc',
'location' => 'SF'
],
];
var_export(merge_by_name($arr1, $arr2));
Result
array (
0 =>
array (
'id' => 1,
'name' => 'test1',
'desc' => 'test_desc',
'quantity' => 3,
'holder' => 'John',
'location' => 'ATL',
),
1 =>
array (
'id' => 2,
'name' => 'test2',
'desc' => 'test_desc',
'quantity' => 33,
),
2 =>
array (
'holder' => 'Jackie',
'name' => 'test3',
'desc' => 'test_desc',
'location' => 'SF',
),
)

Remove array keys that aren't listed in a second array

The following is my result array
Array (
[0] => Array
(
[ProductID] => 220
[TextID] => 477
[ProductName] => Hugo Woman
[Price] => 43.91
[BTW] => 21
[Stock] => 500
[BrandID] => 186
[ProductImage] => https://media.douglas-shop.com/874229/300_0/Hugo_Boss-Hugo_Woman-EdP_30ml_GRATIS_Nail_Polish_4ml.jpg
[CategoryID] => 1
[SubCategoryID] => 1
[View] => 0
)
[1] => Array
(
[ProductID] => 616
[TextID] => 959
[ProductName] => Hugo XY
[Price] => 44.95
[BTW] => 21
[Stock] => 500
[BrandID] => 186
[ProductImage] => https://media.douglas-shop.com/333660/300_0/Hugo_Boss-Hugo_XY.jpg
[CategoryID] => 2
[SubCategoryID] => 2
[View] => 0
)
[2] => Array
(
[ProductID] => 650
[TextID] => 991
[ProductName] => Hugo Just Different
[Price] => 45.76
[BTW] => 21
[Stock] => 500
[BrandID] => 186
[ProductImage] => https://media.douglas-shop.com/617162/300_0/Hugo_Boss-Hugo_Just_Different.jpg
[CategoryID] => 2
[SubCategoryID] => 2
[View] => 0
)
)
I have a second array with subcategories, in which the key is referencing to the SubCategoryID:
Array
(
[1] => Array
(
[EN] => Ladies
[NL] => Dames
)
[2] => Array
(
[EN] => Men
[NL] => Heren
)
)
I want to loop through the result array and remove the keys who don't have a SubCategoryID listed in the second array. I looked at http://php.net/manual/en/function.array-filter.php, but can't figure out the best way to do this.
Thank you!
There are two solutions to the above problem, one with using simple for loop and one with using array_walk() function.
Here, $result_array is your result array and $subcategory_array is your subcategory array.
Solution(1):
$subcategory_ids = array_keys($subcategory_array);
$arrLength = count($result_array);
for($i = 0; $i < $arrLength; ++$i){
if(!in_array($result_array[$i]['SubCategoryID'], $subcategory_ids)){
unset($result_array[$i]);
}
}
// display $result_array
echo "<pre>"; print_r($result_array);
Solution(2):
$subcategory_ids = array_keys($subcategory_array);
function filter_arr($item, $key){
global $result_array, $subcategory_ids;
if(!in_array($item['SubCategoryID'], $subcategory_ids)){
unset($result_array[$key]);
}
}
array_walk($result_array, "filter_arr");
// display $result_array
echo "<pre>"; print_r($result_array);
Please try i thnik this help to you..
$array = array (
0 => array
(
'ProductID' => 220,
'TextID' => 477,
'ProductName' => 'Hugo Woman',
'Price' => 43.91,
'BTW' => 21,
'Stock' => 500,
'BrandID' => 186,
'ProductImage' => 'https://media.douglas-shop.com/874229/300_0/Hugo_Boss-Hugo_Woman-EdP_30ml_GRATIS_Nail_Polish_4ml.jpg',
'CategoryID' => 1,
'SubCategoryID' => 1,
'View' => 0
),
1 => array
(
'ProductID' => 616,
'TextID' => 959,
'ProductName' => 'Hugo XY',
'Price' => 44.95,
'BTW' => 21,
'Stock' => 500,
'BrandID' => 186,
'ProductImage' => 'https://media.douglas-shop.com/333660/300_0/Hugo_Boss-Hugo_XY.jpg',
'CategoryID' => 1,
'SubCategoryID' => 2,
'View' => 0
),
'2' => array
(
'ProductID' => 650,
'TextID' => 991,
'ProductName' => 'Hugo Just Different',
'Price' => 45.76,
'BTW' => 21,
'Stock' => 500,
'BrandID' => 186,
'ProductImage' => 'https://media.douglas-shop.com/617162/300_0/Hugo_Boss-Hugo_Just_Different.jpg',
'CategoryID' => 2,
'SubCategoryID' => 1,
'View' => 0
),);
$array1 = array (
1 => array
(
'EN' => 'Ladies',
'NL' => 'Dames'
),
2 => array
(
'EN' => 'Men',
'NL' => 'Heren'
),);
foreach($array as $newArray){
if (array_key_exists($newArray['SubCategoryID'], $array1)) {
echo '<pre>';
print_r($newArray);
echo '</pre>';}}

Have the following array merged

I have the following array:
Array
(
[0] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[1] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[2] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[3] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[4] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[5] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[6] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
[7] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
[8] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
)
Which is being created with the following code:
$Display_Arr = array();
$Tick = 0;
foreach ($_POST['product'] AS $_1){
if (!in_array($_1['vendor_id'], $Display_Arr)){
$Display_Arr[$Tick] = array(
"Vendor_ID" => $_1['vendor_id'],
"Quantity" => ""
);
$Display_Arr[$Tick]["Quantity"] .= $_1['quantity'];
}else{
$Display_Arr[$Tick]["Quantity"] .= $_1['quantity'];
}
++$Tick;
}
echo "<pre>";
print_r($Display_Arr);
echo "</pre>";
But I am not getting my desired output, which is:
Array
(
[0] => Array
(
[Vendor_ID] => 1
[Quantity] => 55,55,55
)
[1] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[2] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
)
Where am I going wrong with this?
#mathielo
The current output is:
Array
(
[1] => Array
(
[Vendor_ID] => 1
[Quantity] => 55
)
[3] => Array
(
[Vendor_ID] => 3
[Quantity] =>
)
[4] => Array
(
[Vendor_ID] => 4
[Quantity] =>
)
)
Whereas, i'm trying to obtain:
[0] => Array
(
[Vendor_ID] => 1
[Quantity] => 55,55,55
)
If I got it right, what you need is this:
EDIT: Just made some tests and got it right this time:
$Display_Arr = array();
foreach ($_POST['product'] AS $_1){
if (!array_key_exists($_1['Vendor_ID'], $Display_Arr)){
$Display_Arr[$_1['Vendor_ID']] = array(
"Vendor_ID" => $_1['Vendor_ID'],
"Quantity" => $_1['Quantity']
);
}else{
if(!empty($_1['Quantity']))
$Display_Arr[$_1['Vendor_ID']]["Quantity"] .= ",{$_1['Quantity']}";
}
}
echo "<pre>";
print_r($Display_Arr);
echo "</pre>";
The main problem was in if (!in_array($_1['vendor_id'], $Display_Arr)). PHP's in_array() checks for given needle in the array values, and we were trying to match to the Vendor_ID value stored in the outer array keys. That was fixed using array_key_exists().
EDIT 2: I used this for test data:
$_POST['product'] = array(
0 => array(
'Vendor_ID' => 1,
'Quantity' => 55
),
1 => array(
'Vendor_ID' => 1,
'Quantity' => 55
),
2 => array(
'Vendor_ID' => 1,
'Quantity' => 55
)
,
3 => array(
'Vendor_ID' => 3,
'Quantity' => ''
),
4 => array(
'Vendor_ID' => 3,
'Quantity' => ''
),
5 => array(
'Vendor_ID' => 3,
'Quantity' => ''
),
6 => array(
'Vendor_ID' => 4,
'Quantity' => ''
),
7 => array(
'Vendor_ID' => 4,
'Quantity' => ''
),
8 => array(
'Vendor_ID' => 4,
'Quantity' => ''
)
);
You won't be needing $Tick anymore, as you could use Vendor_ID as keys for the outer array.
Looks like the easiest way to solve this would be to first aggregate the vendor quantities, and then build the final array with the keys that you are using.
I am assuming the input looks something like this:
$_POST['product'] = [
['vendor_id' => 1, 'quantity' => 55],
['vendor_id' => 1, 'quantity' => 55],
['vendor_id' => 1, 'quantity' => 55],
['vendor_id' => 3, 'quantity' => null],
['vendor_id' => 3, 'quantity' => null],
['vendor_id' => 3, 'quantity' => null],
['vendor_id' => 4, 'quantity' => null],
['vendor_id' => 4, 'quantity' => null],
['vendor_id' => 4, 'quantity' => null],
];
Aggregating the quantities:
$aggregates = [];
foreach ($_POST['product'] as $product) {
$id = $product['vendor_id'];
if ( ! isset($aggregates[$id])) {
$aggregates[$id] = [];
}
if ($product['quantity'] > 0) {
$aggregates[$id][] = $product['quantity'];
}
}
The aggregates array should now look like this:
$aggregates = [
1 => [
0 => 55,
1 => 55,
2 => 55,
],
3 => [], // Empty
4 => [], // Empty
];
As you can see the data is now neatly organized and ready to be put into any format you want. Using the keys that you use in your question it is as simple as:
$output = [];
foreach ($aggregates as $vid => $qty) {
$quantity = implode(',', $qty);
$output[] = ['Vendor_ID' => $vid, 'Quantity' => $quantity];
}
The output should now look like this:
$output = [
['Vendor_ID' => 1, 'Quantity' => '55,55,55'],
['Vendor_ID' => 3, 'Quantity' => ''],
['Vendor_ID' => 4, 'Quantity' => ''],
];
This will output exactly what you are looking for although the output of the last answer (Sverri M. Olsen) is more useful. Here you get the quantities as a string while with Sverri's method you get an array in first place.
$Display_Arr = array();
$vendors=array();
foreach ($_POST['product'] AS $_1){
if (!in_array($_1['vendor_id'],$vendors)){
$vendors[]=$_1['vendor_id'];
$Display_Arr[sizeof($vendors)-1] = array(
"Vendor_ID" => $_1['vendor_id'],
"Quantity" => $_1['quantity']
);
}
else{
$vendorKey=array_search($_1['vendor_id'],$vendors);
$Display_Arr[$vendorKey]["Quantity"] .=(!empty($Display_Arr[$vendorKey]["Quantity"])?',':null).$_1['quantity'];
}
}

Categories