I am having following array and i want to increment quantity if date are same.
Array (
[0] => Array ( [date] => 2016-02-02 [quantity] => 2 )
[1] => Array ( [date] => 2016-02-04 [quantity] => 1 )
[2] => Array ( [date] => 2016-02-05 [quantity] => 1 )
[3] => Array ( [date] => 2016-02-02 [quantity] => 1 )
[4] => Array ( [date] => 2016-02-03 [quantity] => 1 )
[5] => Array ( [date] => 2016-02-02 [quantity] => 2 )
[6] => Array ( [date] => 2016-02-03 [quantity] => 2 )
[7] => Array ( [date] => 2016-02-04 [quantity] => 2 )
)
for example if 0 index having date 2016-02-02 and quantity 2,and same like 3rd index having same date but different quantity like wise 5th index. Now i want to add only the quantity if date are same and store into new array as
Array (
[0] => Array ( [date] => 2016-02-02 [quantity] => 5 )
[1] => Array ( [date] => 2016-02-04 [quantity] => 3 )
[2] => Array ( [date] => 2016-02-05 [quantity] => 1 )
[4] => Array ( [date] => 2016-02-03 [quantity] => 3 )
)
please explain me how to do such thing in php.
Try this way simply using foreach
$sum = array();
foreach ($array as $item) {
if (!isset($sum[$item['date']])) $sum[$item['date']] = 0;
$sum[$item['date']] += $item['quantity'];
}
print '<pre>';
print_r($sum);
OR
Using array_reduce()
$sum = array_reduce($array, function($result, $item) {
if (!isset($result[$item['date']])) $result[$item['date']] = 0;
$result[$item['date']] += $item['quantity'];
return $result;
}, array());
print '<pre>';
print_r($sum);
you can use array_search(); built in function in some way
a simple example:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
You can use this logic for above task.
foreach($arrayname as $key=>$value)
{
foreach($arrayname as $key1=>$value1)
{
if($value['date']==$value1['date']&&$key!=$key1)
{
$value['quantity']=$value['quantity']+$value1['quantity'];
unset($arrayname[$key]);
}
}
}
Related
I would like to arrange Array before found a specific array key. For example
Following is array.
Array(
[0] => Array([package_name] => 10.4)
[1] => Array([final_total] => 10.4)
[2] => Array([package_name] => 10.5)
[3] => Array([package_name] => 4.5)
[4] => Array([final_total] => 15)
[5] => Array([package_name] => 15.2)
[6] => Array([final_total] => 15.2)
[7] => Array([package_name] => 8.4)
[8] => 8.4
)
And I want like array.
(
[0] => Array
(
[package_name] => array([0]=>10.4),
[final_total] => 10.4
)
[1] => Array
(
[package_name] => array(
[0] => 10.5,
[1] => 4.5
),
[final_total] => 15
)
[2] => Array
(
[package_name] => array([0]=>15.2)
[final_total] => 15.2
)
[3] => Array
(
[package_name] => array([0]=>8.4)
[final_total] => 8.4
)
)
So What i want If final_total key is found from array then set previous values(package_name) of final_total in a array.
Above example you can see there are 4 final_total key's of array so i want to set each package_name's value in a array that are previous value of final_total.
Following is my code.
This is my array
$main = array(array('package_name' => 10.4),array('final_total' => 10.4),array('package_name' => 10.5),array('package_name' => 4.5),array('final_total' => 15)
,array('package_name' => 15.2),array('final_total' => 15.2));
Code.
<?php
$newArray = [];
$newPackag=[];
$previousValue='';
$currentKey=0;
$PreviousKey=0;
$i=0;
$main_keys = array_keys($main);
foreach ($main as $key => $value) {
$curtent_item[] = isset($main[$key]['package_name']) ? $main[$key]['package_name'] : '';
$currentKey = $key;
if(#$main[$key]['final_total'] ==#$value['final_total']){
$previousValue = #$value['package_name'];
$newArray[] = $previousValue;
$myarray= array(#$main[$key]['package_name']);
if (array_key_exists("final_total",$main[$key])){
if($PreviousKey ==0){
$PreviousKey = $key+1;
}else{
$PreviousKey = $key;
}
}else{
$keys = array_keys($main);
$position = array_search($key, $keys);
echo "Curent Key =".$currentKey.'PreviousKey'.$PreviousKey.'</br>';
if($currentKey != $PreviousKey){
$nextKey = $keys[$currentKey+1 ];
}
$newPackag1[] = array('package_name'=>#$myarray);
}
$mainArray = array('package'=>$newPackag1);
}
$i++;
}
echo "<pre>NE page";print_r($newPackag1);
echo "<pre>";print_r($main);
anyone has better and correct solution. Above code which i am trying not able to get desire output.
Here is the snippet with modified data(surely will work for your case too),
$result = [];$i= 0;
foreach ($main as $key => $value) {
if (is_array($value)) {
$k = key($value);$v = array_shift($value);
($k != 'final_total' ? $result[$i][$k][] = $v : $result[$i][$k] = $v);
if($k == 'final_total'){
$i++;
}
} elseif (!empty($value)) {
$result[$i]['final_total'] = $value;
}
}
print_r($result);
Demo
Output:-
Array
(
[0] => Array
(
[package_name] => Array
(
[0] => 6.5
[1] => 9
)
[final_total] => 15.5
)
[1] => Array
(
[package_name] => Array
(
[0] => 10.5
)
[final_total] => 10.5
)
[2] => Array
(
[package_name] => Array
(
[0] => 17.1
)
[final_total] => 17.1
)
[3] => Array
(
[package_name] => Array
(
[0] => 9.8
)
[final_total] => 9.8
)
[4] => Array
(
[package_name] => Array
(
[0] => 16
)
[final_total] => 16
)
[5] => Array
(
[package_name] => Array
(
[0] => 10.5
)
[final_total] => 10.5
)
)
Array
(
[content_type] => Array
(
[0] => story
[1] => delhi
[2] => tez
)
[type] => Array
(
[0] => video_id
[1] => subcategory
[2] => story_id
)
[fetch_id] => Array
(
[0] => 32
[1] => 32
[2] => 2
)
[order] => Array
(
[0] => 6
[1] => 4
[2] => 5
)
[label] => Array
(
[0] => dsfs fdsf dsf sdf
[1] => dfsdfs
[2] => sdfsdfsd
)
[link] => Array
(
[0] => fsd fsdf sdf
[1] => fsdfsdfdsf
[2] => fsdfdsfds
)
[record] => Array
(
[0] => 10
[1] => 8
[2] => 12
)
)
Above is the array I have to sort this array in the basis of order field and it should shorted all the fields accordingly like below example.
$arr['order'][0] = 4;
$arr['order'][1] = 5;
$arr['order'][2] = 6;
$arr['type'][0] = 'subcategory';
$arr['type'][1] = 'story_id';
$arr['type'][2] = 'video_id';
and so on.....
You can try this -
$new = array();
// Extract and get the keys as values
$order = array_flip($array['order']);
// sort them according to keys
ksort($order);
// loop through main array
foreach($array as $key => $sub_array) {
// loop through order
foreach ($order as $o) {
// store the new value according to order
$new[$key][] = $sub_array[$o];
}
}
Demo
Some lesser solution:
asort($array['order']);
foreach ($array as $key => $subArray) {
$array[$key] = array_replace($array['order'], $subArray);
}
For reset a key sequence you may just to use array_values().
I just pasted my sample input & output.
Sample Input:
Array
(
[0] => Array
(
[id] => 1
[msisdn] => 10
[sc] => 8155
)
[1] => Array
(
[id] => 2
[msisdn] => 20
[sc] => 22020
)
[2] => Array
(
[id] => 3
[msisdn] => 10
[sc] => 8155
)
[3] => Array
(
[id] => 4
[msisdn] => 10
[sc] => 8155
)
[4] => Array
(
[id] => 5
[msisdn] => 20
[sc] => 22020
)
[5] => Array
(
[id] => 6
[msisdn] => 30
[sc] => 22020
)
)
Sample Output:
Array
(
[0] => Array
(
[id] => 1,3,4
[msisdn] => 10
[sc] => 8155
)
[1] => Array
(
[id] => 2,5
[msisdn] => 20
[sc] => 22020
)
[2] => Array
(
[id] => 6
[msisdn] => 30
[sc] => 8155
)
)
Just make that particular value that key, then just concatenate when already pushed/exists:
$new_array = array();
foreach ($array as $value) {
if(!isset($new_array[$value['msisdn']])) {
// if not yet pushed, just initialize
$new_array[$value['msisdn']] = $value;
} else {
// if already inside, then just concatenate
$new_array[$value['msisdn']]['id'] .= ', ' . $value['id'];
}
}
$new_array = array_values($new_array);
echo '<pre>';
print_r($new_array);
Sample Output
Live on codepad: http://codepad.org/0fw9k2w9
You can use the fact that in PHP array is an hash map. By creating an intermediate array you can solve this in O(n) time.
$merged = array();
foreach($array as $v) {
$merged[$v['msisdn']][$v['sc']] [] = $v['id'];
}
$final = array();
foreach($merged as $msisdn=>$v) {
foreach($v as $sc=>$ids) {
$final [] = array('msisdn'=>$msisdn,'sc'=>$sc,'id'=>$ids);
}
}
I have a php array that just like this:
Array
(
[0] => Array
(
[product] => 2
[price] => 30
[qnty] => 1
)
[1] => Array
(
[product] => 2
[price] => 30
[qnty] => 1
)
[2] => Array
(
[product] => 1
[price] => 250
[qnty] => 1
)
)
and I want to combine the duplicate values, add "qnty" index value and print that array like this:
Array
(
[0] => Array
(
[product] => 2
[price] => 30
[qnty] =>2
)
[1] => Array
(
[product] => 1
[price] => 250
[qnty] => 1
)
)
How can i combine this array. Please help me
try the code below. I am assuming the your array name is $products
$merged = array();
foreach($products as $product) {
$key = $product['product'];
if(!array_key_exists($key, $merged)) {
$merged[$key] = $product;
}
else {
$merged[$key]['qnty'] += $product['qnty'];
}
}
echo '<pre>';
print_r($merged);
exit;
I have an array and I wish to update the values in roomTotalPrice. However when I loop, it changes to just a variable.
Array I want to change:
Array
(
[10] => Array
(
[12] => Array
(
[num_rooms] => 2
[adults] => Array
(
[0] => 2
[1] => 2
)
[prices] => Array
(
[0] => 44.5
[1] => 44.5
)
[roomTotalPrice] => Array
(
[0] => 44.5
[1] => 44.5
)
[price] => 178
[supp] => 0
)
)
Code I am using:
//Total Room Price
foreach($iroom['roomTotalPrice'] as $irt){
$s_rate[$iraid][$iroid]['roomTotalPrice'] = 100;
}
Array
(
[10] => Array
(
[12] => Array
(
[num_rooms] => 2
[adults] => Array
(
[0] => 2
[1] => 2
)
[prices] => Array
(
[0] => 44.5
[1] => 44.5
)
[roomTotalPrice] => 100
[price] => 178
[supp] => 0
)
)
Use this code:
foreach($iroom['roomTotalPrice'] as &$irt){
$irt = 100;
}
Anyway this code is based on the fact that $iroom['roomTotalPrice'] loop on the right sub-array as you have written.
Are you trying to make the sum for prices ?
$x[10][12][roomTotalPrice] = array_sum($x[10][12][roomTotalPrice])
Assuming that the $iroom variable is the array in your first code sample, I believe you can use the following code to set all 'roomTotalPrice' entries to 100:
foreach ($iroom as $firstLevelIndex => $firstLevelArray) {
foreach ($firstLevelArray as $secondLevelIndex => $secondLevelArray) {
$iroom[$firstLevelIndex][$secondLevelIndex]['roomTotalPrice'] = 100;
}
}
Is this what your want?
foreach ($iroom as $k1 => $v1) { // Loop outer array
foreach ($v1 as $k2 => $v2) if (isset($v2['roomTotalPrice'])) { // Loop inner arrays and make sure they have a roomTotalPrice key
foreach ($v2['roomTotalPrice'] as $k3 => $v3) { // Loop roomTotalPrice array
$iroom[$k1][$k2]['roomTotalPrice'][$k3] = 100; // Change the values
}
}
}