group mysql results in multidimensional array - php

I have the following:
$variants = [
0 => [
"variant_name" => "iPhone 5",
"sku_id" => "2",
"sku" => "GLC-IPH5REDXXXL",
"stock_total" => "10",
"stock_left" => "10",
"retail_price" => 1000,
"on_sale_price" => 0
],
1 => [
"variant_name" => "Red",
"sku_id" => "2",
"sku" => "GLC-IPH5REDXXXL",
"stock_total" => "10",
"stock_left" => "10",
"retail_price" => 1000,
"on_sale_price" => 0
],
2 => [
"variant_name" => "iPhone 6s Plus",
"sku_id" => "4",
"sku" => "GLC-IPH6SP",
"stock_total" => "5",
"stock_left" => "5",
"retail_price" => 1000,
"on_sale_price" => 0
],
3 => [
"variant_name" => "iPhone 6s",
"sku_id" => "13",
"sku" => "GLC-IPH6S",
"stock_total" => "5",
"stock_left" => "5",
"retail_price" => 1000,
"on_sale_price" => 0
]
]
I would like to put them in the following array
0 => [
"sku_id" => "2",
"sku" => "GLC-IPH5REDXXXL",
"stock_total" => "10",
"stock_left" => "10",
"retail_price" => 1000,
"on_sale_price" => 0,
"options" => ['iPhone 4', 'Red'],
"option1" => 'iPhone4',
"option2" => 'Red',
"option3" => null
],
1 => [
"sku_id" => "4",
"sku" => "GLC-IPH6SP",
"stock_total" => "5",
"stock_left" => "5",
"retail_price" => 1000,
"on_sale_price" => 0,
"options" => ['iPhone 6s Plus'],
"option1" => 'iPhone 6s Plus',
"option2" => null,
"option3" => null
],
2 => [
"sku_id" => "13",
"sku" => "GLC-IPH6S",
"stock_total" => "5",
"stock_left" => "5",
"retail_price" => 1000,
"on_sale_price" => 0,
"options" => ['iPhone 6s'],
"option1" => 'iPhone 6s',
"option2" => null,
"option3" => null
]
I can't fill the options with each variant_name
I can't set the option1, option2, option3 with each corresponding variant_name
I've tried a simple foreach($variants as $v) loop on the first array and I got it working until options, option1, option2, option3 from which I get the repeating values.
I just can't figure it out how to do it, any suggestions?

You could use a simple foreach() and perhaps a for(). The for() here is a little inefficient because it runs every time, so it's highly repetitive and continually overwrites...but it works:
foreach($variants as $rows) {
$sku[$rows['sku_id']]['sku_id'] = $rows['sku_id'];
$sku[$rows['sku_id']]['sku'] = $rows['sku'];
$sku[$rows['sku_id']]['stock_total'] = $rows['stock_total'];
$sku[$rows['sku_id']]['stock_left'] = $rows['stock_left'];
$sku[$rows['sku_id']]['retail_price'] = $rows['retail_price'];
$sku[$rows['sku_id']]['on_sale_price'] = $rows['on_sale_price'];
$sku[$rows['sku_id']]['options'][] = $rows['variant_name'];
for($i = 0; $i < 3; $i++)
$sku[$rows['sku_id']]['option'.($i+1)] = (isset($sku[$rows['sku_id']]['options'][$i]))? $sku[$rows['sku_id']]['options'][$i] : NULL;
}
echo print_r(array_values($sku));
Gives you:
Array
(
[0] => Array
(
[sku] => GLC-IPH5REDXXXL
[stock_total] => 10
[stock_left] => 10
[retail_price] => 1000
[on_sale_price] => 0
[options] => Array
(
[0] => iPhone 5
[1] => Red
)
[option1] => iPhone 5
[option2] => Red
[option3] =>
)
[1] => Array
(
[sku] => GLC-IPH6SP
[stock_total] => 5
[stock_left] => 5
[retail_price] => 1000
[on_sale_price] => 0
[options] => Array
(
[0] => iPhone 6s Plus
)
[option1] => iPhone 6s Plus
[option2] =>
[option3] =>
)
[2] => Array
(
[sku] => GLC-IPH6S
[stock_total] => 5
[stock_left] => 5
[retail_price] => 1000
[on_sale_price] => 0
[options] => Array
(
[0] => iPhone 6s
)
[option1] => iPhone 6s
[option2] =>
[option3] =>
)
)

Solution
$result = [];
foreach($variants as $v) {
$result[$v['sku_id']]['sku_id'] = $v['sku_id'];
$result[$v['sku_id']]['sku'] = $v['sku'];
$result[$v['sku_id']]['stock_left'] = $v['stock_left'];
$result[$v['sku_id']]['retail_price'] = price($v['retail_price']);
$result[$v['sku_id']]['options'][] = $v['variant_name'];
if(isset($result[$v['sku_id']]['options'][0])) {
$result[$v['sku_id']]['option1'] = $result[$v['sku_id']]['options'][0];
}
else {
$result[$v['sku_id']]['option1'] = null;
}
if(isset($result[$v['sku_id']]['options'][1])) {
$result[$v['sku_id']]['option2'] = $result[$v['sku_id']]['options'][1];
}
else {
$result[$v['sku_id']]['option2'] = null;
}
if(isset($result[$v['sku_id']]['options'][2])) {
$result[$v['sku_id']]['option3'] = $result[$v['sku_id']]['options'][2];
}
else {
$result[$v['sku_id']]['option3'] = null;
}
}
return $result;

Related

unset values null array multidimensional php [duplicate]

This question already has answers here:
Recursively remove empty elements and subarrays from a multi-dimensional array
(8 answers)
How to remove null values in multi-dimensional array?
(7 answers)
Closed 1 year ago.
this is my first time on stackoverflow so sorry if I do something wrong. I would also appreciate your advice.
I have the next Array:
$dataPayment= [
"operationType" => null
"terminal" => 12345
"payment" => array:14 [
"terminal" => 12345
"order" => "1234519997"
"amount" => 100
"currency" => "EUR"
"secure" => 0
"idUser" => 123456789"
"tokenUser" => "zidkeKeu68Kld"
"urlOk" => null
"urlKo" => null
"originalIp" => "1.130.151.28"
"methodId" => 1
"trxType" => "N"
"userInteraction" => 1
"scaException" => "MIT"
]
"subscription" => array:2 [
"startDate" => null
"endDate" => null
]
]
And I want delete the null values. With array_filter also delete values 0, but I need those values 0. I tried with the following method:
private function arrayUnset( $dataPayment )
{
foreach( $dataPayment as $key => $value )
{
if( is_array( $dataPayment[ $key ] ) )
{
$this->arrayUnset( $dataPayment[ $key ] );
}
if( $value === null || $value === "" )
{
unset( $dataPayment[ $key ] );
}
}
return $dataPayment;
}
But, only delete the first value.
$dataPayment = [
"terminal" => 12345
"payment" => array:14 [
"terminal" => 12345
"order" => "1234519997"
"amount" => 100
"currency" => "EUR"
"secure" => 0
"idUser" => 123456789"
"tokenUser" => "zidkeKeu68Kld"
"urlOk" => null
"urlKo" => null
"originalIp" => "1.130.151.28"
"methodId" => 1
"trxType" => "N"
"userInteraction" => 1
"scaException" => "MIT"
]
"subscription" => array:2 [
"startDate" => null
"endDate" => null
]
]
And I would need the following array:
$dataPayment = [
"terminal" => 12345
"payment" => array:14 [
"terminal" => 12345
"order" => "1234519997"
"amount" => 100
"currency" => "EUR"
"secure" => 0
"idUser" => 123456789"
"tokenUser" => "zidkeKeu68Kld"
"originalIp" => "1.130.151.28"
"methodId" => 1
"trxType" => "N"
"userInteraction" => 1
"scaException" => "MIT"
]
]
Can you help me please?. Thanks.
That code does not seem to delete the 0 valued entries, but you do need to pass the parameter by reference if you want to see the changes in the calling process
$Payment = [
"operationType" => null,
"terminal" => 12345,
"payment" => [
"terminal" => 12345,
"order" => "1234519997",
"amount" => 100,
"currency" => "EUR",
"secure" => 0,
"idUser" => 123456789,
"tokenUser" => "zidkeKeu68Kld",
"urlOk" => null,
"urlKo" => null,
"originalIp" => "1.130.151.28",
"methodId" => 1,
"trxType" => "N",
"userInteraction" => 1,
"scaException" => "MIT"
],
"subscription" => [
"startDate" => null,
"endDate" => null
]
];
class xxx
{
private function arrayUnset( &$dataPayment )
{
foreach( $dataPayment as $key => $value ) {
if( is_array( $dataPayment[ $key ] ) ) {
$this->arrayUnset( $dataPayment[ $key ] );
}
if( $value === null || $value === "" ) {
unset( $dataPayment[ $key ] );
}
}
return $dataPayment;
}
public function zzz($data)
{
return $this->arrayUnset($data);
}
}
$obj = new xxx;
print_r($obj->zzz($Payment));
RESULTS
Array
(
[terminal] => 12345
[payment] => Array
(
[terminal] => 12345
[order] => 1234519997
[amount] => 100
[currency] => EUR
[secure] => 0
[idUser] => 123456789
[tokenUser] => zidkeKeu68Kld
[originalIp] => 1.130.151.28
[methodId] => 1
[trxType] => N
[userInteraction] => 1
[scaException] => MIT
)
[subscription] => Array
(
)
)
You should passing argument by reference.
private function arrayUnset( &$dataPayment )
{
foreach( $dataPayment as $key => $value )
{
if( is_array( $dataPayment[ $key ] ) )
{
$dataPayment[ $key ] = $this->arrayUnset($value);
}
if( $value === null || $value === "" )
{
unset( $dataPayment[ $key ] );
}
}
return $dataPayment;
}
Array filters remove null elements, so map your array using mapWithKeys, if each property is an array, use array_filter(). Run a secondary filter, to remove the empty array.
$collection = collect($dataPayment);
$result = $collection->mapWithKeys(function ($item, $key) {
if (is_array($item)) {
$item = array_filter($item);
}
return [$key => $item];
})->filter()->all();
This should produce the expected results. If any problems with the code, please write.
You are not storing the return from your recursive calls.
Try:
<?php
$Payment = [
"operationType" => null,
"terminal" => 12345,
"payment" => [
"terminal" => 12345,
"order" => "1234519997",
"amount" => 100,
"currency" => "EUR",
"secure" => 0,
"idUser" => 123456789,
"tokenUser" => "zidkeKeu68Kld",
"urlOk" => null,
"urlKo" => null,
"originalIp" => "1.130.151.28",
"methodId" => 1,
"trxType" => "N",
"userInteraction" => 1,
"scaException" => "MIT"
],
"subscription" => [
"startDate" => null,
"endDate" => null
]
];
function arrayUnset($dataPayment) {
foreach($dataPayment as $key => $value)
if(is_array($dataPayment[$key]))
$dataPayment[$key]=arrayUnset($dataPayment[$key]);
else if ($value==null || $value=="")
unset($dataPayment[$key]);
return $dataPayment;
}
print_r(arrayUnset($Payment));
Output:
Array
(
[terminal] => 12345
[payment] => Array
(
[terminal] => 12345
[order] => 1234519997
[amount] => 100
[currency] => EUR
[secure] => 0
[idUser] => 123456789
[tokenUser] => zidkeKeu68Kld
[originalIp] => 1.130.151.28
[methodId] => 1
[trxType] => N
[userInteraction] => 1
[scaException] => MIT
)
[subscription] => Array
(
)
)
Teh Playground!

How to remove any sub array and keep only two top levels of a multidimensional array?

I need to modify an array with subarrays and keep only the top two arrays (array -> results - x) and remove any subarray below. For example array "location" & "syncState" should be removed.
Original array:
$device_array = [
"totalCount" => "3",
"results" => [
[
"id" => "2",
"serialNumber" => "DX",
"location" => ["id" => "5", "locationName" => "US"]
],
[
"id" => "4",
"serialNumber" => "DM",
"syncState" => ["id" => "7", "locationName" => "DE"]
],
[
"id" => "5",
"serialNumber" => "C0"
]
]
];
The array should look like this:
Array
(
[totalCount] => 3
[results] => Array
(
[0] => Array
(
[id] => 2
[serialNumber] => DX
)
[1] => Array
(
[id] => 4
[serialNumber] => DM
)
[2] => Array
(
[id] => 5
[serialNumber] => C0
)
)
)
I'm trying to loop through the arrays (sub arrays included) but I can't remove all of the subarrays that sit under $device_array['results'][x].
foreach ($device_array as $key => $value) {
if(is_array($value)) {
unset($device_array['results'][0]['location']);
}
}
You can just loop the results subarray directly and write a custom filter which will modify each entry by reference. Any of the associative elements that hold array type data will be filtered out.
Code: (Demo)
$array = [
"totalCount" => "3",
"results" => [
[
"id" => "2",
"serialNumber" => "DX",
"location" => ["id" => "5", "locationName" => "US"]
],
[
"id" => "4",
"serialNumber" => "DM",
"syncState" => ["id" => "7", "locationName" => "DE"]
],
[
"id" => "5",
"serialNumber" => "C0"
]
]
];
foreach ($array['results'] as &$entry) {
$entry = array_filter($entry, 'is_scalar');
}
var_export($array);
Output:
array (
'totalCount' => '3',
'results' =>
array (
0 =>
array (
'id' => '2',
'serialNumber' => 'DX',
),
1 =>
array (
'id' => '4',
'serialNumber' => 'DM',
),
2 =>
array (
'id' => '5',
'serialNumber' => 'C0',
),
),
)
Or completely functional style: (Demo)
$array['results'] = array_map(
function($entry) {
return array_filter($entry, 'is_scalar');
},
$array['results']
);
var_export($array);
This is how you obtain the output, but I am not so sure if this is what you need in your case
<?php
$array = [
'total' => 2,
'result' => [
[
'id' => 1,
'serialNumber' => 'DX',
'location' => ['id'=>1, 'locationName'=>'US']
],
[
'id' => 2 ,
'serialNumber' => 'DO',
'syncState' => ['id'=>7, 'locationName'=>'DE']
]
]
];
foreach( $array['result'] as $key => $value ){
foreach($value as $key2=>$subarray){
if(is_array($subarray)){
unset($value[$key2]);
}
}
$array['result'][$key] = $value;
}
print_r($array);

Search associative array for specific value based on set variable

I'm retrieving some JSON that I am converting to an associative array. The issue that I am having is I am trying to get the email value from the user's who id matches the value that I have already set as a variable.
Here is what the array looks like
Array
(
[object] => list
[data] => Array
(
[0] => Array
(
[object] => pro
[id] => pro_77c9c6a85d814e059a6a2690989bae29
[first_name] => Jane
[last_name] => Doe
[full_name] => Jane Doe
[initials] => JD
[email] => admin#testorg.com
[mobile_number] => 9998761234
[messaging_uuid] => 4547c231c3e7d0ff1796f47b88f166d5
[color_hex] => EF9159
[avatar_url] => /assets/add_image.png
[avatar_thumb_url] =>
[has_avatar] =>
[organization_name] => testorg
[is_admin] => 1
[permissions] => Array
(
[show_company_setup] => 1
[can_see_home_data] => 1
[show_reporting] => 1
)
[is_super_pro] =>
[is_archived] =>
[impersonated] =>
)
[1] => Array
(
[object] => pro
[id] => pro_0fcb8e8610e54c518078db77ced7530e
[first_name] => Robert
[last_name] => Jordan
[full_name] => Robert Jordan
[initials] => RJ
[email] => rj#testorg.com
[mobile_number] => 4547457742
[messaging_uuid] => 0fcb8e8610e54c518078db77ced7530e
[color_hex] => EF9159
[avatar_url] => /assets/add_image.png
[avatar_thumb_url] =>
[has_avatar] =>
[organization_name] => testorg
[is_admin] => 1
[permissions] => Array
(
[show_company_setup] => 1
[can_see_home_data] => 1
[show_reporting] => 1
)
[is_super_pro] =>
[is_archived] =>
[impersonated] =>
)
)
[url] => /pros
)
Im basically trying to match the value that I have set in my pro_id variable
pro_0fcb8e8610e54c518078db77ced7530e
To the 'ID' Key in the array above and get the 'email' value associated to that same array and store for use later in my code.
Here is what I have so far, but no joy
foreach ($proObject as $key => $value) {
if ($key['id'] == $pro_id)
$techmail = $key['email'];
}
From my understanding of your question, and if you want to get only one element, you should be able to use array_search with array_column to get the index of the searched element. Using that you can then access the element and its corresponding email value. If you might expect more than one element I would use array_filter.
One Element:
In short:
$i = array_search($pro_id, array_column($proObject, 'id'));
$element = ($i !== false ? $proObject[$i] : null);
print_r($element["email"]);
Full code:
<?php
$proObject = array(
array(
"object" => "pro",
"id" => "pro_77c9c6a85d814e059a6a2690989bae29",
"first_name" => "Jane",
"last_name" => "Doe",
"full_name" => "Jane Doe",
"initials" => "JD",
"email" => "admin#testorg.com",
"mobile_number" => "9998761234",
"messaging_uuid" => "4547c231c3e7d0ff1796f47b88f166d5",
"color_hex" => "EF9159",
"avatar_url" => "/assets/add_image.png",
"avatar_thumb_url" => "",
"has_avatar" => "",
"organization_name" => "testorg",
"is_admin" => "1",
"permissions" => array(
"show_company_setup" => "1",
"can_see_home_data" => "1",
"show_reporting" => "1",
) ,
"is_super_pro" => "",
"is_archived" => "",
"impersonated" => "",
) ,
array(
"object" => "pro",
"id" => "pro_0fcb8e8610e54c518078db77ced7530e",
"first_name" => "Robert",
"last_name" => "Jordan",
"full_name" => "Robert Jordan",
"initials" => "RJ",
"email" => "rj#testorg.com",
"mobile_number" => "4547457742",
"messaging_uuid" => "0fcb8e8610e54c518078db77ced7530e",
"color_hex" => "EF9159",
"avatar_url" => "/assets/add_image.png",
"avatar_thumb_url" => "",
"has_avatar" => "",
"organization_name" => "testorg",
"is_admin" => "1",
"permissions" => array(
"show_company_setup" => "1",
"can_see_home_data" => "1",
"show_reporting" => "1",
) ,
"is_super_pro" => "",
"is_archived" => "",
"impersonated" => "",
)
);
$pro_id = "pro_0fcb8e8610e54c518078db77ced7530e";
$i = array_search($pro_id, array_column($proObject, 'id'));
$element = ($i !== false ? $proObject[$i] : null);
print_r($element["email"]);
?>
Multiple Elements:
In short:
class idEqualsFilter {
private $id;
public function __construct($id) {
$this->id = $id;
}
function __invoke($i) {
return $this->id === $i["id"];
}
};
$elements = array_filter($proObject, new idEqualsFilter($pro_id));
print_r(array_column($elements, "email"));
Full code:
<?php
$proObject = array(
array(
"object" => "pro",
"id" => "pro_77c9c6a85d814e059a6a2690989bae29",
"first_name" => "Jane",
"last_name" => "Doe",
"full_name" => "Jane Doe",
"initials" => "JD",
"email" => "admin#testorg.com",
"mobile_number" => "9998761234",
"messaging_uuid" => "4547c231c3e7d0ff1796f47b88f166d5",
"color_hex" => "EF9159",
"avatar_url" => "/assets/add_image.png",
"avatar_thumb_url" => "",
"has_avatar" => "",
"organization_name" => "testorg",
"is_admin" => "1",
"permissions" => array
(
"show_company_setup" => "1",
"can_see_home_data" => "1",
"show_reporting" => "1",
),
"is_super_pro" => "",
"is_archived" => "",
"impersonated" => "",
),
array(
"object" => "pro",
"id" => "pro_0fcb8e8610e54c518078db77ced7530e",
"first_name" => "Robert",
"last_name" => "Jordan",
"full_name" => "Robert Jordan",
"initials" => "RJ",
"email" => "rj#testorg.com",
"mobile_number" => "4547457742",
"messaging_uuid" => "0fcb8e8610e54c518078db77ced7530e",
"color_hex" => "EF9159",
"avatar_url" => "/assets/add_image.png",
"avatar_thumb_url" => "",
"has_avatar" => "",
"organization_name" => "testorg",
"is_admin" => "1",
"permissions" => array
(
"show_company_setup" => "1",
"can_see_home_data" => "1",
"show_reporting" => "1",
),
"is_super_pro" => "",
"is_archived" => "",
"impersonated" => "",
)
);
$pro_id = "pro_0fcb8e8610e54c518078db77ced7530e";
class idEqualsFilter {
private $id;
public function __construct($id) {
$this->id = $id;
}
function __invoke($i) {
return $this->id === $i["id"];
}
};
$elements = array_filter($proObject, new idEqualsFilter($pro_id));
print_r(array_column($elements, "email"));
?>

Map Array in child in php

I have 2 arrays in php which look like following:
array1 = [product_id = [data], product_id = [data], ..]
[
101 => [
"sku" => "AB01"
],
201 => [
"sky" => "AB02"
],
...
]
array2 = attribute of product with product_id
[
0 => [
"product_id" => 101,
"name" => "pro 1"
],
1 => [
"product_id" => 101,
"size" => "S"
],
2 => [
"product_id" => 201,
"name" => "pro 2"
],
3 => [
"product_id" => 201,
"size" => "S"
],
...
]
What I want is according to product_id in array2 data is pushed in array1 as child array like this
[
101 => [
"sku" => "AB01",
"attributes" => [
0 => [
"product_id" => 101,
"name" => "pro 1"
],
1 => [
"product_id" => 101,
"size" => "S"
]
]
],
201 => [
"sky" => "AB02",
"attributes" => [
0 => [
"product_id" => 201,
"name" => "pro 2"
],
1 => [
"product_id" => 201,
"size" => "S"
]
]
],
...
]
Array length is around 1000 for array1 and >5000 for array2. foreach loop taking too much time. Is there any fast way to achieve it?
About the fastest way I can think of achieving this is using a foreach loop over the second array, as your first array is indexed by the product_id, it is easy to directly insert the new data on each loop...
foreach ( $array2 as $item ) {
$array1[$item['product_id']]['attributes'][] = $item;
}
Maybe it helps you
$array1 = [
101 => [
"sku" => "AB01"
],
201 => [
"sky" => "AB02"
]
];
$array2 = [
0 => [
"product_id" => 101,
"name" => "pro 1"
],
1 => [
"product_id" => 101,
"size" => "S"
],
2 => [
"product_id" => 201,
"name" => "pro 2"
],
3 => [
"product_id" => 201,
"size" => "S"
]
] ;
foreach ($array2 as $result){
if(array_key_exists($result['product_id'], $array1)) {
$array1[$result['product_id']]['attributes'][] = $result;
}
}
print_r($array1);
your result look like this
Array
(
[101] => Array
(
[sku] => AB01
[attributes] => Array
(
[0] => Array
(
[product_id] => 101
[name] => pro 1
)
[1] => Array
(
[product_id] => 101
[size] => S
)
)
)
[201] => Array
(
[sky] => AB02
[attributes] => Array
(
[0] => Array
(
[product_id] => 201
[name] => pro 2
)
[1] => Array
(
[product_id] => 201
[size] => S
)
)
)
)
$arr1=[
101 => [
"sku" => "AB01"
],
201 => [
"sky" => "AB02"
]
];
$arr2=[
0 => [
"product_id" => 101,
"name" => "pro 1"
],
1 => [
"product_id" => 101,
"size" => "S"
],
2 => [
"product_id" => 201,
"name" => "pro 2"
],
3 => [
"product_id" => 201,
"size" => "S"
]
];
foreach ($arr2 as $arr_val ) {
$arr1[$arr_val['product_id']]['attributes'][] = $arr_val;
}
echo "<pre>"; print_r($arr1);
I hope this answer work for you
first array
$arr = [
101 => [
"sku" => "AB01"
],
201 => [
"sky" => "AB02"
],
];
second array
$arr2 = [
0 => [
"product_id" => 101,
"name" => "pro 1"
],
1 => [
"product_id" => 101,
"size" => "S"
],
2 => [
"product_id" => 201,
"name" => "pro 2"
],
3 => [
"product_id" => 201,
"size" => "S"
],
];
finally this what i try to do
$newArr = [];
forEach($arr as $product_id => $product_value){
$attrArr = [];
forEach($arr2 as $key => $value){
if($product_id == $value['product_id']){
$attrArr[] = $value;
$newArr[$product_id] = [
array_keys($product_value)[0] => array_values($product_value)[0],
];
}
}
$newArr[$product_id]['attributes'] = $attrArr;
}
echo '<pre>';
print_r($newArr);
echo '</pre>';

Group and Calculate Values in Array

I have an array like the following:
Array
(
[0] => Array
(
[0] => Array
(
[Product_Name] => Apple Pie - 8"
[Product_Qty] => 1
[Product_Cat] => Pies
)
[1] => Array
(
[Product_Name] => Pecan Pie - 8"
[Product_Qty] => 1
[Product_Cat] => Pies
)
)
[1] => Array
(
[0] => Array
(
[Product_Name] => Apple Pie - 8"
[Product_Qty] => 1
[Product_Cat] => Pies
)
)
[2] => Array
(
[0] => Array
(
[Product_Name] => Strawberry Pie - 8"
[Product_Qty] => 1
[Product_Cat] => Pies
)
[1] => Array
(
[Product_Name] => Pecan Pie - 8"
[Product_Qty] => 1
[Product_Cat] => Pies
)
)
[3] => Array
(
[0] => Array
(
[Product_Name] => Lemon Pie - 8"
[Product_Qty] => 1
[Product_Cat] => Pies
)
[1] => Array
(
[Product_Name] => Pecan Pie - 8"
[Product_Qty] => 1
[Product_Cat] => Pies
)
)
)
I'm trying to group by same Product_Name and also add up the Product_Qty in each. Any help is greatly appreciated.
You can create a double loop and sum all value of every different product under a different array key as below:
$myArr = [
0 => [
0 => [
"Product_Name" => "Apple Pie - 8",
"Product_Qty" => 1,
"Product_Cat" => "Pies"
],
1 => [
"Product_Name" => "Apple Pie - 8",
"Product_Qty" => 1,
"Product_Cat" => "Pies"
]
],
1 => [
0 => [
"Product_Name" => "Pecan Pie - 8",
"Product_Qty" => 1,
"Product_Cat" => "Pies"
]
],
2 => [
0 => [
"Product_Name" => "Strawberry Pie - 8",
"Product_Qty" => 1,
"Product_Cat" => "Pies"
],
1 => [
"Product_Name" => "Pecan Pie - 8",
"Product_Qty" => 1,
"Product_Cat" => "Pies"
]
],
3 => [
0 => [
"Product_Name" => "Lemon Pie - 8",
"Product_Qty" => 1,
"Product_Cat" => "Pies"
],
1 => [
"Product_Name" => "Pecan Pie - 8",
"Product_Qty" => 1,
"Product_Cat" => "Pies"
]
]
];
$total = [];
foreach($myArr as $group){
foreach($group as $item){
$total[$item["Product_Name"]] = isset($total[$item["Product_Name"]]) ? $total[$item["Product_Name"]] + $item["Product_Qty"] : $item["Product_Qty"];
}
}
var_dump($total);
It will provide that total:
array(4) {
["Apple Pie - 8"]=>
int(2)
["Pecan Pie - 8"]=>
int(3)
["Strawberry Pie - 8"]=>
int(1)
["Lemon Pie - 8"]=>
int(1)
}
If you want to get all data as in array now then you can run below code.
$finalArray = array();
$product_name_arr = array();
foreach ($array as $key => $value) {
foreach ($value as $sub_key => $sub_value) {
if(in_array($sub_value['Product_Name'], $product_name_arr)){
foreach ($finalArray as $fa_key => $fa_value) {
if($fa_value['Product_Name'] == $sub_value['Product_Name']){
$finalArray[$fa_key]['Product_Qty'] = $finalArray[$fa_key]['Product_Qty'] + $sub_value['Product_Qty'];
}
}
} else {
$product_name_arr[] = $sub_value['Product_Name'];
$finalArray[] = $sub_value;
}
}
}

Categories