I have the following array:
[0] => Array
(
[id] => 1
[uid] => 50
[sum1] => 1
[sum2] => 2
)
[1] => Array
(
[id] => 2
[uid] => 50
[sum1] => 2
[sum2] => 4
)
[2] => Array
(
[id] => 3
[uid] => 51
[sum1] => 3
[sum2] => 5
)
As you can see, on some of those indexes, [uid] is the same. The length and data of the array is dynamic.
what i need to do is merge the indexes that have the same value for[uid] and sum the values for the other keys:
[0] => Array
(
[id] => 2
[uid] => 50
[sum1] => 3
[sum2] => 6
)
[1] => Array
(
[id] => 3
[uid] => 51
[sum1] => 3
[sum2] => 5
)
But for the life of me, i can't figure out how to do that.
Any help appreciated!
You can do it like this way,
<?php
$mainArray = [
0 => Array
(
'id' => 1,
'uid' => 50,
'sum1' => 1,
'sum2' => 2
),
1 => Array
(
'id' => 2,
'uid' => 50,
'sum1' => 2,
'sum2' => 4
),
2 => Array
(
'id' => 3,
'uid' => 51,
'sum1' => 3,
'sum2' => 5
)
];
$newArray=[];
foreach ($mainArray as $value) {
if(!array_key_exists($value['uid'], $newArray)){
// Store first time
$newArray[$value['uid']] = $value;
}else{
// Already exist, then sum and replace it
$newArray[$value['uid']]['id'] = $value['id'];
$newArray[$value['uid']]['sum1'] += $value['sum1'];// Sum with previous value
$newArray[$value['uid']]['sum2'] += $value['sum2'];// Sum with previous value
}
}
$newArray = array_values($newArray);// Reset indexes, Start the array index with zero
print_r($newArray);// To see the output
Output:
Array
(
[0] => Array
(
[id] => 2
[uid] => 50
[sum1] => 3
[sum2] => 6
)
[1] => Array
(
[id] => 3
[uid] => 51
[sum1] => 3
[sum2] => 5
)
)
I think you are correct. Actually, i solved the problem using something similar:
$sumArray = Array();
foreach ($array1 as $item){
if(isset($sumArray[$item['uid']])){
$sumArray[$item['idPartener']]['sum1'] += $item['sum1'];
$sumArray[$item['idPartener']]['sum2'] += $item['sum2'];
}else{
$sumArray[$item['uid']] = Array(
'id' => $item['id'],
'sum1' => $item['sum1'],
'sum2' => $item['sum2'] ,
);
}
}
Thanks all for your help!
Related
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
)
)
I want to remove the first.. how to say that outside of the array and left inside array of a multidimension array. I couldn't found out the solution.. someone knows how to do it??
This is my code. I assign a array and i try to put into another array like this.
$final_sku = array();
foreach($skus as $sku){
foreach($sku as $key => $s){
$final_sku[] = array('Sku' => $s);
}
}
$newArray = array(
"Product" => array(
"PrimaryCategory" => "1",
"AssociatedSku" => "12",
"Attributes" => array(
),
"Skus" => $final_sku
)
);
And this is the $final_sku output be like.
[0] => Array
(
[Sku] => Array
(
[package_weight] => 5
[package_length] => 4
[package_width] => 3
[package_height] => 2
[package_content] =>
[tax_class] => default
[color_family] => Antique White
[price] => 4
[special_price] =>
[SellerSku] => sku1
[variation] => var1
)
)
[1] => Array
(
[Sku] => Array
(
[package_weight] => 5
[package_length] => 4
[package_width] => 3
[package_height] => 2
[package_content] =>
[tax_class] => default
[color_family] => Apricot
[price] => 4
[special_price] =>
[SellerSku] => sku2
[variation] => var1
)
)
I want the output be like this.
[Sku] => Array
(
[package_weight] => 5
[package_length] => 4
[package_width] => 3
[package_height] => 2
[package_content] =>
[tax_class] => default
[color_family] => Antique White
[price] => 4
[special_price] =>
[SellerSku] => sku1
[variation] => var1
)
[Sku] => Array
(
[package_weight] => 5
[package_length] => 4
[package_width] => 3
[package_height] => 2
[package_content] =>
[tax_class] => default
[color_family] => Apricot
[price] => 4
[special_price] =>
[SellerSku] => sku2
[variation] => var1
)
UPDATE: I want to pass the array and convert to xml. So the array key would be duplicated.
It does not make sense to have the same array of 2 members under the same key.
If you want to access one of them, what will be its uniqueness over the other?
The logical solution is
[sku] => [
0 => [first sku data....],
1 => [sku data....],
]
I have the following array:
Array
(
[0] => Array
(
[hotelID] => 10
[hotelcategoryID] => 12
[hotelName] => Grand Forest Metsovo
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 2
)
[1] => Array
(
[hotelID] => 10
[hotelcategoryID] => 12
[hotelName] => Grand Forest Metsovo
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 3
)
[2] => Array
(
[hotelID] => 10
[hotelcategoryID] => 12
[hotelName] => Grand Forest Metsovo
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 4
)
[3] => Array
(
[hotelID] => 14
[hotelcategoryID] => 7
[hotelName] => Hotel Metropolis
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 23
)
[4] => Array
(
[hotelID] => 14
[hotelcategoryID] => 7
[hotelName] => Hotel Metropolis
[hotelShortDescription] =>
[hotelVisible] => 1
[roomID] => 24
)
)
I have two different hotelID keys. I would like to extract only one element (the first one) where the hotelID is unique in whole array. I am trying with following code:
$data['uniqueHotels'] = array_map('unserialize', array_unique(array_map('serialize', $hotels)));
but without any luck so far.
Anyone can give me a hint?
If looking for the first element:
<?php
$hotels = array(
array(
'id' => 1,
'hotelID' => 10
),
array(
'id' => 2,
'hotelID' => 10,
),
array(
'id' => 3,
'hotelID' => 20,
),
array(
'id' => 4,
'hotelID' => 20,
),
);
function getUniqueHotels($hotels) {
$uniqueHotels = array();
foreach($hotels as $hotel) {
$niddle = $hotel['hotelID'];
if(array_key_exists($niddle, $uniqueHotels)) continue;
$uniqueHotels[$niddle] = $hotel;
}
return $uniqueHotels;
}
$unique_hotels = getUniqueHotels($hotels);
print_r($unique_hotels);
results in:
Array
(
[10] => Array
(
[id] => 1
[hotelID] => 10
)
[20] => Array
(
[id] => 3
[hotelID] => 20
)
)
You could simply loop through the array and add them to a new array, indexed by hotelID. This way any duplicates will just overwrite the existing value and you end up with one entry per hotel:
$unique = array();
foreach ($hotels as $value)
{
$unique[$value['hotelID']] = $value;
}
$data['uniqueHotels'] = array_values($unique);
Here is a dynmaic solution:
function uniqueAssocArray($array, $uniqueKey){
$unique = array();
foreach ($array as $value){
$unique[$value[$uniqueKey]] = $value;
}
$data = array_values($unique);
return $data;
}
How to use:
uniqueAssocArray($yourArray, 'theKey');
along the lines of what you're trying,
array_unique(array_map(function($hotel) { return $hotel['hotelID']; }, $array))
$series = array();
while($row = mysql_fetch_assoc($result)) {
$series[$row["data_id"]][] = $row;
}
The output from a print_r on $series yields for two example series:
Array (
[1] => Array ( [0] => Array ( [id] => 1 [data_id] => 1 [time_id] => 1
[data] => 1 ) [1] => Array ( [id] => 2 [data_id] => 1 [time_id] => 2
[data] => 3 ) )
[2] => Array ( [0] => Array ( [id] => 6 [data_id] => 2 [time_id] => 1
[data] => 7 ) [1] => Array ( [id] => 7 [data_id] => 2 [time_id] => 2
[data] => 4 ) )
My question: how do I unset the multidimensional array so it contains only [data] and none of the other keys? I still want $series to contain [1] and [2] but I do not want the respective sub-arrays to contain any other keys other than [data].
In fact, since I am reducing the subarrays to contain a single key, I would really like to get rid of the subarrays altogether so that I have two arrays:
$series[1] = array(1,3) and
$series[2] = array(7,4)
Try this :
$series = array();
while($row = mysql_fetch_assoc($result)) {
$series[$row["data_id"]][] = $row['data'];
}
I think you can loop in your array and build a new one keeping only data details
$array = array ('1' => array ( '0' => array ( 'id' => 1, 'data_id' => 1, 'time_id' => 1, 'data' => 1 ), '1' => array ( 'id' => 2, 'data_id' => 1, 'time_id' => 2, 'data' => 3 ), ),
'2' => array ( '0' => array ( 'id' => 6, 'data_id' => 2, 'time_id' => 1, 'data' => 7 ), '1' => array ( 'id' => 7, 'data_id' => 2, 'time_id' => 2, 'data' => 4 ) ));
$i= 0;
$n= 0;
$series = array();
foreach($array as $dato)
{
$series[$i] = array();
foreach($dato as $data)
{
foreach($data as $key => $value)
{
if($key == 'data')
{
$series[$i][$n] = $value;
$n++;
}
}
}
$n = 0;
$i++;
}
var_dump($series);
This will output
array (size=2)
0 =>
array (size=2)
0 => int 1
1 => int 3
1 =>
array (size=2)
0 => int 7
1 => int 4
Live demo
Trying to convert a "grouped" multidimensional array to a "segmented" multidimensional array. Not sure how to explain it exactly so hopefully these print_r results explain it better.
Current Array
Array
(
[qty] => Array
(
[0] => 1
[1] => 1
[2] => 1
)
[item_id] => Array
(
[0] => RR332
[1] => FF586
[2] => QW865
)
[item_name] => Array
(
[0] => Widget 1
[1] => Widget 2
[2] => Widget 3
)
[price] => Array
(
[0] => 1.00
[1] => 1.50
[2] => 1.50
)
)
Wanted Array
Array
(
[0] => Array
(
[qty] => 1
[item_id] => RR332
[item_name] => Widget 1
[price] => 1.00
)
[1] => Array
(
[qty] => 1
[item_id] => FF586
[item_name] => Widget 2
[price] => 1.50
)
[2] => Array
(
[qty] => 1
[item_id] => QW865
[item_name] => Widget 3
[price] => 1.50
)
)
This seems like it should be a simple task but I haven't been able to crack it yet.
I would preferably like to loop through the Current Array to create the Wanted Array if possible.
Any help is greatly appreciated!
Thanks.
You mean this?:
$data = array(
'qty' => array(
0 => 1,
1 => 1,
2 => 1,
),
'item_id' => array(
0 => 'RR332',
1 => 'FF586',
2 => 'QW865',
),
'item_name' => array(
0 => 'Widget 1',
1 => 'Widget 2',
2 => 'Widget 3',
),
'price' => array(
0 => '1.00',
1 => '1.50',
2 => '1.50',
),
);
$result = array();
foreach($data as $key => $values)
{
foreach($values as $number => $value)
$result[$number][$key] = $value;
}
print_r($result);
Output:
Array
(
[0] => Array
(
[qty] => 1
[item_id] => RR332
[item_name] => Widget 1
[price] => 1.00
)
[1] => Array
(
[qty] => 1
[item_id] => FF586
[item_name] => Widget 2
[price] => 1.50
)
[2] => Array
(
[qty] => 1
[item_id] => QW865
[item_name] => Widget 3
[price] => 1.50
)
)
I think this will do the job for you, though I don't have a good data set to test against.
$wanted_array = array();
// Iterate over the outer array to get the text keys & inner arrays
foreach ($current_array as $txtkey=>$arr) {
// Iterate over each inner array to get the numeric key
foreach ($arr as $numkey=>$val) {
// Set a numeric key pointing to a new array
// onto the new outer array if it isn't already there
if (!isset($wanted_array[$numkey])) $wanted_array[$numkey] = array();
// Swap the keys of the outer and inner arrays.
$wanted_array[$numkey][$txtkey] = $val;
}
}
Update: Using test array from #hakre's answer, here it is in practice:
$current_array = array(
'qty' => array(
0 => 1,
1 => 1,
2 => 1
),
'item_id' => array(
0 => 'RR332',
1 => 'FF586',
2 => 'QW865'
),
'item_name' => array(
0 => 'Widget 1',
1 => 'Widget 2',
2 => 'Widget 3'
),
'price' => array(
0 => '1.00',
1 => '1.50',
2 => '1.50'
)
);
// Output:
Array
(
[0] => Array
(
[qty] => 1
[item_id] => RR332
[item_name] => Widget 1
[price] => 1.00
)
[1] => Array
(
[qty] => 1
[item_id] => FF586
[item_name] => Widget 2
[price] => 1.50
)
[2] => Array
(
[qty] => 1
[item_id] => QW865
[item_name] => Widget 3
[price] => 1.50
)
)
Like you said, just loop through it to build it.
$wanted = array();
foreach($current['item_id'] as $key => $value) {
$wanted[$key] = array(
'qty' = $current['qty'][$key],
'item_id' = $current['item_id'][$key],
'item_name' = $current['item_name'][$key],
'price' = $current['price'][$key]
);
}
print_r($wanted);
You can loop over your original array using the foreach loop, which gives you the $key, and $value for each item in your array. From there, construct your new array as you like.
$array2 = array();
foreach ($array1 as $key => $value)
{
$array2[] = array('key' => 'value');
}