Modify array contents - php

I've used
unset($quotes_array[0]['methods'][0]);
$quotes_array[0]['methods'] = array_values($quotes_array[0]['methods']);
to remove the first element of an array, but the selection form where the array is used no longer responds correctly to the radio button selected by the user.
The original array looked like this:
Array
(
[0] => Array
(
[id] => advshipper
[methods] => Array
(
[0] => Array
(
[id] => 1-0-0
[title] => Trade Shipping
[cost] => 20
[icon] =>
[shipping_ts] =>
[quote_i] => 0
)
[1] => Array
(
[id] => 2-0-0
[title] => 1-2 working days
[cost] => 3.2916666666667
[icon] =>
[shipping_ts] =>
[quote_i] => 1
)
[2] => Array
(
[id] => 4-0-0
[title] => 2-3 working days
[cost] => 2.4916666666667
[icon] =>
[shipping_ts] =>
[quote_i] => 2
)
[3] => Array
(
[id] => 8-0-0
[title] => Click & Collect
[cost] => 0
[icon] =>
[shipping_ts] =>
[quote_i] => 3
)
)
[module] => Shipping
[tax] => 20
)
)
And the modified array looks like this:
Array
(
[0] => Array
(
[id] => advshipper
[methods] => Array
(
[0] => Array
(
[id] => 2-0-0
[title] => 1-2 working days
[cost] => 3.2916666666667
[icon] =>
[shipping_ts] =>
[quote_i] => 1
)
[1] => Array
(
[id] => 4-0-0
[title] => 2-3 working days
[cost] => 2.4916666666667
[icon] =>
[shipping_ts] =>
[quote_i] => 2
)
[2] => Array
(
[id] => 8-0-0
[title] => Click & Collect
[cost] => 0
[icon] =>
[shipping_ts] =>
[quote_i] => 3
)
)
[module] => Shipping
[tax] => 20
)
)
I suspect the problem is caused by the fact that in the modified array, [quote_i] now starts at 1, and not 0 as in the original. So i have [quote_i] as 1, 2 then 3 but it should be 0, 1, then 2.
I've tried using array_walk to correct this, but not been successful.
Any suggestions on a solution to this?

The trick basically would be to correct quote_i
$counter = 0;
foreach ($quotes_array[0]['methods'] as $key => $value)
{
$quotes_array[0]['methods'][$key]['quote_i'] = $counter;
$counter++;
}

Using array_walk with example code that should match your use case
<?php
foreach ($quotes_array[0]['methods'] as $a) {
$a = array(
array('quote_i' => 1),
array('quote_i' => 2),
array('quote_i' => 3)
);
array_walk($a, function(&$item, $key) {
$item['quote_i'] = $item['quote_i'] - 1;
});
var_dump($a);
// array([0] => array('quote_i' => 0), [1] => array('quote_i' => 1), [2] => array('quote_id' => 2))
}

Related

PHP sum array values with same keys

This is the original main array:
Array
(
[0] => Array
(
[subtotal] => 0.6000
[taxes] => 0.0720
[charged_amount] => 0.6720
[total_discount] => 0.0000
[provinceName] => BC
[store_key] => 1
[store_id] => 5834
[categories] => Array
(
[2] => 0.6000
[4] => 0
[3] => 0
)
)
[1] => Array
(
[subtotal] => 29.8500
[taxes] => 2.3270
[charged_amount] => 20.2370
[total_discount] => 11.9400
[provinceName] => MB
[store_key] => 9
[store_id] => 1022
[categories] => Array
(
[2] => 0
[4] => 29.8500
[3] => 0
)
)
[2] => Array
(
[subtotal] => 0.3000
[taxes] => 0.0390
[charged_amount] => 0.3390
[total_discount] => 0.0000
[provinceName] => NB
[store_key] => 8
[store_id] => 1013
[categories] => Array
(
[2] => 0.3000
[4] => 0
[3] => 0
)
)
[3] => Array
(
[subtotal] => 24.3100
[taxes] => 1.1830
[charged_amount] => 10.2830
[total_discount] => 15.2100
[provinceName] => NL
[store_key] => 4
[store_id] => 3033
[categories] => Array
(
[2] => 24.3100
[4] => 0
[3] => 0
)
)
[4] => Array
(
[subtotal] => 1116.3400
[taxes] => 127.6960
[charged_amount] => 1110.0060
[total_discount] => 134.0300
[provinceName] => ON
[store_key] => 2
[store_id] => 1139
[categories] => Array
(
[2] => 85.7300
[4] => 143.2800
[3] => 887.3300
)
)
[5] => Array
(
[subtotal] => 10.8500
[taxes] => 1.4100
[charged_amount] => 12.2600
[total_discount] => 0.0000
[provinceName] => ON
[store_key] => 5
[store_id] => 1116
[categories] => Array
(
[2] => 10.8500
[4] => 0
[3] => 0
)
)
)
I just need to add the values of the array [categories] with same keys and use it further to print the total, but not getting correct output, can someone help me out to get the desired result:
Desired result
An array with same keys but total of individual array values
Array ( [2] => 0.9000 [4] => 29.8500 [3] => 1.5 )
NOTE: Initial array is dynamic can have n number of key value pair
Thanks
The first thing that you need to do is iterate through the outer array. Then, for each row in the outer array, you and to iterate through each entry in the category element. So this means that we have two foreach loops. Inside the inner foreach, we simply set the value for the current index to be the value of the same index on a 'sum' array (if it doesn't already exist), or increment the value of that index if it already exists in the 'sum' array.
<?php
$sumArray = array();
foreach($outerArray as $row)
{
foreach($row["categories"] as $index => $value)
{
$sumArray[$index] = (isset($sumArray[$index]) ? $sumArray[$index] + $value : $value);
}
}
?>
Demo using your example array

Delete an array element based on value from nested array

I have try to remove whole parent array using PHP unset(key) function based on value from a nested array in it.
Nested array looks like
Array (
[0] => Array (
[ID] => 9909
[SHIPPING_AMOUNT] => 5
[TOTAL_TAX] => 0
[GRAND_AMOUNT] => 49.97
[ITEMS_AMOUNT] => 44.97
[ITEMS] => Array (
[0] => Array (
[CODE] => TEST
[QTY] => 1
[UNIT_PRICE] => 14.99 )
[1] => Array (
[CODE] => NNKIT
[QTY] => 1
[UNIT_PRICE] => 9.99 )
[2] => Array (
[CODE] => MAINKIT
[QTY] => 1
[UNIT_PRICE] => 19.99 )
)
)
[1] => Array (
[ID] => 9910
[SHIPPING_AMOUNT] => 5
[TOTAL_TAX] => 0
[GRAND_AMOUNT] => 74.96
[ITEMS_AMOUNT] => 69.96
[ITEMS] => Array (
[0] => Array (
[CODE] => NNKIT
[QTY] => 1
[UNIT_PRICE] => 9.99 )
[1] => Array (
[CODE] => MAINKIT
[QTY] => 3
[UNIT_PRICE] => 19.99 )
)
)
[2] => Array (
[ID] => 9911
[SHIPPING_AMOUNT] => 5
[TOTAL_TAX] => 0
[GRAND_AMOUNT] => 44.98
[ITEMS_AMOUNT] => 39.98
[ITEMS] => Array (
[0] => Array (
[CODE] => MAINKIT
[QTY] => 2
[UNIT_PRICE] => 19.99 )
)
)
[3] => Array (
[ID] => 9912
[SHIPPING_AMOUNT] => 5
[TOTAL_TAX] => 0
[GRAND_AMOUNT] => 29.98
[ITEMS_AMOUNT] => 24.98
[ITEMS] => Array (
[0] => Array (
[CODE] => TEST
[QTY] => 1
[UNIT_PRICE] => 14.99 )
[1] => Array (
[CODE] => NEWTEST
[QTY] => 1
[UNIT_PRICE] => 9.99 )
)
)
and value which I check for is CODE = MAINKIT. If not exists in a nested array then main array should be removed (in this case parent array[3]) but somehow returned key is from nested array not a parent one.
PHP code:
foreach($array as $key => $value){
if(is_array($value) && $value['CODE'] != 'MAINKIT')
unset($key);
}
The CODE elements are inside the $value['ITEMS'] array, not directly in $value.
To tell whether MAINKIT isn't in any of the items, you have to loop through all the items, testing whether any of them matches. If none do, then delete the array element.
Try:
foreach($array as $key => $value){
if (is_array($value) && is_array($value['ITEMS']))
$found_mainkit = false;
foreach ($value['ITEMS'] as $item) {
if($item['CODE'] == 'MAINKIT') {
$found_mainkit = true;
break;
}
}
if (!$found_mainkit) {
unset($array[$key]);
}
}
}

How to remove duplicate data in an array?

I have the following array:
Array
(
[0] => Array
(
[Import] => Array
(
[product_id] => 1
[id] => 1
[category_id] => 1
[amount] => 50
[cost] => 8320
[paid] => 0
[comment] => transportation and others cost: 100
[created] => 2015-06-22 12:09:20
)
[0] => Array
(
[total_sell] => 6
)
)
[1] => Array
(
[Import] => Array
(
[product_id] => 2
[id] => 2
[category_id] => 2
[amount] => 15
[cost] => 3000
[paid] => 0
[comment] =>
[created] => 2015-06-22 12:10:36
)
[0] => Array
(
[total_sell] => 1
)
)
[2] => Array
(
[Import] => Array
(
[product_id] => 1
[id] => 3
[category_id] => 1
[amount] => 15
[cost] => 2000
[paid] => 0
[comment] =>
[created] => 2015-06-22 12:10:58
)
[0] => Array
(
[total_sell] => 6
)
)
[3] => Array
(
[Import] => Array
(
[product_id] => 1
[id] => 4
[category_id] => 1
[amount] => 50
[cost] => 8000
[paid] => 0
[comment] =>
[created] => 2015-06-23 01:10:10
)
[0] => Array
(
[total_sell] => 6
)
)
)
I want to remove duplicate entry of [Import][product_id]. So my expected result is :
Array
(
[0] => Array
(
[Import] => Array
(
[product_id] => 1
[id] => 1
[category_id] => 1
[amount] => 50
[cost] => 8320
[paid] => 0
[comment] => transportation and others cost: 100
[created] => 2015-06-22 12:09:20
)
[0] => Array
(
[total_sell] => 6
)
)
[1] => Array
(
[Import] => Array
(
[product_id] => 2
[id] => 2
[category_id] => 2
[amount] => 15
[cost] => 3000
[paid] => 0
[comment] =>
[created] => 2015-06-22 12:10:36
)
[0] => Array
(
[total_sell] => 1
)
)
)
Would you write a function to filter this type of array and produce expected result. I have been googling for 2 days but no luck.
This is a handy one liner that should do the trick:
$unique= array_map("unserialize", array_unique(array_map("serialize", $original)));
If the underlying arrays are not identical, that won't work, in which case I think you could do:
$unique = array_intersect_key($original ,
array_unique(
array_map(function($item) {
return $item['Import']['product_id'];
}, $original)
)
);
Tested: http://sandbox.onlinephpfunctions.com/code/8aee5cbd614e0ddd1a03dfaa7e98c72fbbe7d68d
Here is a quick stable sort and reduce which runs in linearithmic time. First-encountered product Id's are kept, and entries with duplicate product Id's are ignored.
// Stable sort
sort($in);
// Reduce
$out = array_reduce($in, function(&$acc, &$item){
if($item['Import']['product_id'] !== #$acc[sizeof($acc)-1]['Import']['product_id']) {
$acc[] = $item;
}
return $acc;
}, []);
Demo: http://ideone.com/BP0eUJ
Update: Here is an even better linear-time algorithm that does the same as above using a fast "hash table" lookup. Again, the first-encountered product Id is kept and subsequent ones of the same Id are ignored.
$out = [];
$hashTable = [];
foreach($in as $item) {
$pid = $item['Import']['product_id'];
if(!isset($hashTable[$pid])) {
$out[] = $item;
$hashTable[$pid] = true;
}
}
Demo: http://ideone.com/5RF0og

Array - how to replace record with newly added

I got the array below and I would like to keep recent added record which is [2] and delete others
Array (
[0] => Array ( [id] => 1 [is_sub] => 0 [product] => New [quantity] => 1 [price] => [total_item_price] => 0 [comments] => )
[1] => Array ( [id] => 1 [is_sub] => 0 [product] => Old [quantity] => 1 [price] => [total_item_price] => 0 [comments] => )
[2] => Array ( [id] => 4 [is_sub] => 0 [product] => Mix [quantity] => 1 [price] => [total_item_price] => 0 [comments] => ) )
i got an answer thanks for helping.
$last = array_slice($orders, -1, 1, true);
Shorter:
$last = array_pop($orders);
$last_data = array_pop($data);
print_r($last_data);

Retrieve multiple data from Array

I asked this question few months ago but at that time i needed to pull just one membership level, now i need to pull every level name, here is array:
Array
(
[success] => 1
[member] => Array
(
[0] => Array
(
[Levels] => Array
(
[1391447566] => stdClass Object
(
[Level_ID] => 1391447566
[Name] => Team Membership
[Cancelled] =>
[CancelDate] =>
[Pending] =>
[UnConfirmed] =>
[Expired] =>
ExpiryDate] => 1397266537
[SequentialCancelled] =>
[Active] => 1
[Status] => Array
(
[0] => Active
)
[Timestamp] => 1394588137
[TxnID] => WL-1-1391447566
)
[1391540448] => stdClass Object
(
[Level_ID] => 1391540448
[Name] => Gold Training Membership
[Cancelled] =>
[CancelDate] =>
[Pending] =>
[UnConfirmed] =>
[Expired] =>
[ExpiryDate] => 1396642789
[SequentialCancelled] =>
[Active] => 1
[Status] => Array
(
[0] => Active
)
[Timestamp] => 1393967989
[TxnID] => WL-1-1391540448
)
[1391540567] => stdClass Object
(
[Level_ID] => 1391540567
[Name] => Platinum Training Membership
[Cancelled] =>
[CancelDate] =>
[Pending] =>
[UnConfirmed] =>
[Expired] =>
[ExpiryDate] => 1397302237
[SequentialCancelled] =>
[Active] => 1
[Status] => Array
(
[0] => Active
)
[Timestamp] => 1394623837
[TxnID] => WL-1-1391540567
)
)
[PayPerPosts] => Array
(
)
)
)
[supported_verbs] => Array
(
[0] => GET
[1] => PUT
[2] => DELETE
)
)
What I need is to pull Name of Level which is inside an object that has diffrent number every time and add it to an array which i need to save in DB. One solution, just to pull info, wass:
foreach ($response["member"][0]["Levels"] AS $level_key => $level_val) {
$level_name = $level_key->Name;
echo 'Name: '.$level_name;
}
but its not pulling anything, just echoing "name" 3 times.
This was the code i used to pull only one name:
$levels = $response["member"][0]["Levels"];
$firstLevel = array_shift(array_values($levels));
$membership = $firstLevel->Name;
Thanks!
Just try with:
$level_name = $level_val->Name;
$level_key is an integer value with level ID (?). $level_val is your level object with data.

Categories