How to sum same array in php [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to sum array in same key and different value.
Array
(
0 => Array
(
'locker_id' => 3,
'locker_model' => 1,
'qty' => 2
),
1 => Array
(
'locker_id' => 3,
'locker_model' => 1,
'qty' => 1
),
2 => Array
(
'locker_id' => 2,
'locker_model' => 1,
'qty' => 2
),
3 => Array
(
'locker_id' => 3,
'locker_model' => 1,
'qty' => 2
),
4 => Array
(
'locker_id' => 2,
'locker_model' => 1,
'qty' => 2
)
);
I want Output it
Array
(
0 => Array
(
'locker_id' => 3,
'locker_model' => 1,
'qty' => 5
),
1 => Array
(
'locker_id' => 2,
'locker_model' => 1,
'qty' => 4
)
);
Thanks.

You could browse your array while creating a new one with keys like "locker_id-locker_model", then you can easily check if your locker exists in this array with array_key_exists function.
$inputArray = array( ... ); // this is your message array
$outputArray = array();
foreach( $inputArray as $locker )
{
if( !array_key_exists( $locker["locker_id"]."-".$locker["locker_model"], $outputArray ) )
{
$outputArray[ $locker["locker_id"]."-".$locker["locker_model"] ] = array(
"locker_id" => $locker["locker_id"],
"locker_model" => $locker["locker_model"],
"qty" => 0
);
}
$outputArray[ $locker["locker_id"]."-".$locker["locker_model"] ]["qty"]++;
}
var_dump( $outputArray );

$dataArr = array
(
0 => array
(
'locker_id' => 3,
'locker_model' => 1,
'qty' => 2
),
1 => array
(
'locker_id' => 3,
'locker_model' => 1,
'qty' => 1
),
2 => array
(
'locker_id' => 2,
'locker_model' => 1,
'qty' => 2
),
3 => array
(
'locker_id' => 3,
'locker_model' => 1,
'qty' => 2
),
4 => array
(
'locker_id' => 2,
'locker_model' => 1,
'qty' => 2
)
);
$sumArr = array();
if(count($dataArr)>0){
foreach($dataArr as $data){
if(!isset($sumArr[$data['locker_id']])){
$sumArr[$data['locker_id']] = $data;
}
$sumArr[$data['locker_id']]['qty'] +=$data['qty'];
}
}
echo "<pre>";print_r($sumArr);

Considering $array1 is your first array,
$array2 = array();
foreach($array1 as $k=>$v) {
if(!isset($array2[$v['locker_id']])) {
$array2[$v['locker_id']] = $v;
} else {
$array2[$v['locker_id']]['qty'] += $v['qty'];
}
}
print_r($array2);

Try this
$arr is your array
$j = 0;
$new = array();
$new[0][qty];
for($i=0;$i<arraylength;$i++){
foreach($arr as $key => $value) {
if($arr[$i][lockerid] == $arr[$key][lockerid]) {
$new[$j][lockerid] = $arr[$key][lockerid];
$new[$j][lockermodel] = $arr[$key][lockermodel];
$new[$j][qty] = $new[$i][qty] + $arr[$key][qty];
J++;
}
}
}

$result = array();
foreach($array as $key => $value){
if(isset($value['locker_id'])){
$result[$value['locker_id']]['qty'] += $value['qty'];
}
else{
$result[$value['locker_id']] = $value;
}
}
You have to loop over your array and save it to another let's say $result. In $result you should put the locker_id as key and then you only have to verify if that key exists. If it is you add the qty value, if isn't you have to add the entire new item.

try this
$ARR_OUTPUT = array();
// $arr will contains your input array
foreach($arr as $arr_val)
{
$locker_id = $arr_val['locker_id'];
$locker_model = $arr_val['locker_id'];
$qty = $arr_val['locker_id'];
if(isset($ARR_OUTPUT[$locker_id][$locker_model]))
{
$ARR_OUTPUT[$locker_id][$locker_model] += $qty;
}
else
{
$ARR_OUTPUT[$locker_id][$locker_model] = $qty;
}
}
echo "<pre>";
print_r($ARR_OUTPUT);
$ARR_OUTPUT2 = array();
foreach($ARR_OUTPUT as $locker_id=>$arr_values)
{
foreach($arr_values as $locker_model=>$qty)
{
$arr_temp['locker_id'] = $locker_id;
$arr_temp['locker_model'] = $locker_model;
$arr_temp['qty'] = $qty;
$ARR_OUTPUT2[] = $arr_temp;
}
}
echo "<pre>";
print_r($ARR_OUTPUT2);

Related

How to merge two arrays diferents on one

How to update an array of objects, adding the quantities if you already have the same ID, or if you have not created a new object.
I tried to explain in the code with the arrays and also with the idea of how I would like the result to be.
old Array
$a1 = [
array(
"id" => 1,
"qty" => 1
),
array(
"id" => 2,
"qty" => 1
)
];
$a2 = [
array(
"id" => 1,
"qty" => 1
)
];
$output = array_merge($a1, $a2);
echo '<pre>';
print_r($output);
echo '</pre>';
Result Error:
Array
(
[0] => Array
(
[id] => 1
[qty] => 1
)
[1] => Array
(
[id] => 2
[qty] => 1
)
[2] => Array
(
[id] => 1
[qty] => 1
)
)
What I need, in addition to if the ID does not contain, add.
Array
(
[0] => Array
(
[id] => 1
[qty] => 2
)
[1] => Array
(
[id] => 2
[qty] => 1
)
)
You can take the first array as base, then search for the key (if existing) where the product matches the id. Then either add the quantity and recalculate the price or you just add the reformatted element (id to product conversion).
$result = $a;
foreach($b as $element) {
$matchingProductIndex = array_search($element['id'], array_column($a, 'product'));
if ($matchingProductIndex !== false) {
$pricePerUnit = $result[$matchingProductIndex]['price'] / $result[$matchingProductIndex]['qty'];
$result[$matchingProductIndex]['qty'] += $element['qty'];
$result[$matchingProductIndex]['price'] = $result[$matchingProductIndex]['qty'] * $pricePerUnit;
} else {
$result[] = [
'qty' => $element['qty'],
'product' => $element['id'],
'price' => $element['price'],
];
}
}
print_r($result);
Working example.
Loop through both arrays with foreach and check the ids against each other.
https://paiza.io/projects/lnnl5HeJSFIOz_6KD6HRIw
<?php
$arr1 = [['qty' => 4, 'id' => 4],['qty' => 1,'id' => 30]];
$arr2 = [['id' => 30, 'qty' => 19],['id' => 31, 'qty' => 2]];
$arr3 = [];
foreach($arr1 as $iArr1){
$match = false;
foreach($arr2 as $iArr2){
if($iArr1['id'] === $iArr2['id']){
$arr3[] = ['id' => $iArr1['id'], 'qty' => $iArr1['qty'] + $iArr2['qty']];
$match = true;
}
}
if(!$match){
$arr3[] = $iArr1;
$arr3[] = $iArr2;
}
}
print_r($arr3);
?>
One approach could be one I more often suggested.
First lets merge $a2 with one to simplify looping over one larger collection.
If we then create a small mapping from id to its index in the result array we can update the running total of qty.
$map = [];
$result = [];
// Merge the two and do as per usual, create a mapping
// from id to index and update the qty at the corresponding index.
foreach (array_merge($a1, $a2) as $subarr) {
$id = $subarr['id'];
if (!key_exists($id, $map)) {
$index = array_push($result, $subarr) - 1;
$map[$id] = $index;
continue;
}
$result[$map[$id]]['qty'] += $subarr['qty'];
}
echo '<pre>', print_r($result, true), '</pre>';
Output:
Array
(
[0] => Array
(
[id] => 1
[qty] => 2
)
[1] => Array
(
[id] => 2
[qty] => 1
)
)

Create new array based on element position

I have an array like so
$dataArray = array(
array( 20800, 21679, 0 ),
array( 15254, 0, 3726 ),
array( 17426, 2973, 0 ),
array( 4391, 37, 0 ),
array( 39194, 435, 0 )
);
I am creating a sub array from this. Any value greater than 2000 becomes a 1, otherwise it becomes a 0.
foreach ($dataArray as $row => $data) {
foreach ($data as $key => $value) {
if($value > 1999) {
$dataArray[$row][$key] = 1;
} else {
$dataArray[$row][$key] = 0;
}
}
}
This produces the following
$dataArray = array(
array( 1, 1, 0 ),
array( 1, 0, 1 ),
array( 1, 1, 0 ),
array( 1, 0, 0 ),
array( 1, 0, 0 )
);
Now what I am trying to do is produce another array that shows the positions of the 1's within the above array. Each row should be represented by a new array. The output I am looking for is this
$dataArray = array(
array( 1, 2 ),
array( 1, 3 ),
array( 1, 2 ),
array( 1 ),
array( 1 )
);
So I can see that row 1 has a 1 in position 1 and 2, row 2 has a 1 in positions 1 and 3 etc.
I wanted to make use of my current loop, so I am trying something like this
$position = array();
foreach ($dataArray as $row => $data) {
foreach ($data as $key => $value) {
if($value > 1999) {
$position[$row] = $key + 1;
$dataArray[$row][$key] = 1;
} else {
$dataArray[$row][$key] = 0;
}
}
}
But this seems way off according to my output. How can I achieve what I am after?
Thanks
<?php
$dataArray = array(
array( 20800, 21679, 0 ),
array( 15254, 0, 3726 ),
array( 17426, 2973, 0 ),
array( 4391, 37, 0 ),
array( 39194, 435, 0 )
);
$endResult = [];
foreach ($dataArray as $key => $value) {
foreach ($value as $subkey => $subvalue) {
if ($subvalue >= 2000) {
$endResult[$key][] = $subkey +1;
}
}
}
print_r($endResult);
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 1
[1] => 3
)
[2] => Array
(
[0] => 1
[1] => 2
)
[3] => Array
(
[0] => 1
)
[4] => Array
(
[0] => 1
)
)
You could use array_map along with array_keys:
$dataArray = [
[1, 1, 0],
[1, 0, 1],
[1, 1, 0],
[1, 0, 0],
[1, 0, 0]
];
$onePositions = array_map(function($row) {
return array_map(function($position) { return $position + 1; }, array_keys($row, 1));
}, $dataArray);
echo '<pre>'; var_dump($onePositions); echo '</pre>';
Demo here
You can make use of the second parameter in the array_keys() function to get the positions after you populate the ones and zeros:
$position = array();
$binary = array();
foreach ($dataArray as $row => $data) {
// if you want to have the positions start at 1 instead of 0
// add a dummy value to the final array
$binary[$row][] = 0;
foreach ($data as $key => $value) {
if($value > 1999) {
$binary[$row][] = 1;
} else {
$binary[$row][] = 0;
}
}
$positions[] = array_keys($binary[$row], 1);
}
Demo Here

JSON - Display only certain data in php

This is my json data as an array, and it is in the file data.json, I tried to parse the data using php, but I am not able show the result using a for loop.
array (
'data' =>
array (
0 =>
array (
'a' => 3222,
'b' => 3,
),
1 =>
array (
'a' => 3221,
'b' => 3,
),
2 =>
array (
'a' => 2215,
'b' => 2,
),
3 =>
array (
'a' => 2214,
'b' => 2,
),
4 =>
array (
'a' => 3218,
'b' => 2,
),
5 =>
array (
'a' => 3217,
'b' => 3,
),
6 =>
array (
'a' => 3216,
'b' => 3,
),
7 =>
array (
'a' => 1235,
'b' => 1,
),
8 =>
array (
'a' => 1234,
'b' => 1,
),
9 =>
array (
'a' => 1233,
'b' => 1,
),
10 =>
array (
'a' => 3213,
'b' => 3,
)
)
I want to display only the data, which is "b=3" which contains the maximum value of "a".
Here is my code, which displays all the results of "a" as a string. All the data is shown as a list.
<?php
$json = file_get_contents('data.json');
$data = json_decode($json,true);
$q = $data['data'];
$length = count($q);
for ($i = 0; $i<$length ; $i++){
if ($q[$i]['b']==3){
$pc = $q[$i]['a'];
echo $pc;
echo "<br>";
}
}
This is not the result I was expected.
One way to solve this could be to check the current value of $pc against the latest value;
If that is higher, then overwrite it:
$q = $data['data'];
$length = count($q);
$max = 0;
for ($i = 0; $i<$length ; $i++){
if ($q[$i]['b']==3){
$pc = $q[$i]['a'];
if ($pc > $max) {
$max = $pc;
}
}
}
echo $max; //3222
Another option could be to use array_map and max:
$result = max(array_map(function($x){
if($x['b'] === 3) return $x['a'];
}, $q
));
echo $result; //3222

How to encode an associative array grouping one of its members?

How to encode an associative array grouping one of its members?
$my_array = Array(
// customer 1
[0] => Array
(
[customer_id] => 1
[cutomer_item] => 7
)
[1] => Array
(
[customer_id] => 1
[cutomer_item] => 9
)
// customer 2
[2] => Array
(
[customer_id] => 2
[cutomer_item] => 3
)
[3] => Array
(
[customer_id] => 2
[cutomer_item] => 5
)
);
I wanto to group (csv) customers_items like:
[
// customer 1
{
"customer_id" : "1" // customer id preserved
"cutomer_items" : "7,9" // customer items imploded with a comma
}
,
// customer 2
{
"customer_id" : "2"
"cutomer_items" : "3,5"
}
]
I got confused with so many array functions (http://php.net/manual/en/ref.array.php).
You can use group_concat function in mysql query. if u are fetching the result through mysql
Here is an idea:
Code
<?php
$my_array = array(
array('customer_id' => 1, 'cutomer_item' => 7),
array('customer_id' => 1, 'cutomer_item' => 9),
array('customer_id' => 2, 'cutomer_item' => 3),
array('customer_id' => 2, 'cutomer_item' => 7),
);
sort($my_array);
$customer = '';
$gp_array = array();
$carr = false;
foreach($my_array as $item) {
if ($customer!=$item['customer_id']) {
if ($carr!==false) {
$carr['customer_items'] = implode(',',$carr['customer_items']);
$gp_array[] = $carr;
}
$carr = array('customer_id'=>$item['customer_id'], 'customer_items' => array());
}
$customer = $item['customer_id'];
$carr['customer_items'][] = $item['cutomer_item'];
}
if ($carr!==false) {
$carr['customer_items'] = implode(',',$carr['customer_items']);
$gp_array[] = $carr;
}
$json = json_encode($gp_array);
echo $json
?>
Output
[{"customer_id":1,"customer_items":"7,9"},{"customer_id":2,"customer_items":"3,7"}]

Counting values within multidimensional arrays?

I have a large array where I basically need to count the number of uniques:
example array
The end result I am looking for something like
$result = array(
'A3D5' => array('P2' => 1, 'P3' => 1, 'P4' => 1, 'total' => 3),
'AE5S' => array('P4' => 1, 'total' => 1)
);
I've tried foreaching through but can't seem to figure out how to sort them into another key, something like $zone = "P{$array['zone']}"; $result[$zone][$prestige]++ or seems to kind of not work or just error.
$array = array(
"denizen" => array
(
"prestige" => 2,
"zone" => "A3D5",
"scope_frag" => 765
),
"생각" => array
(
"prestige" => 4,
"zone" => "A3D5",
"scope_frag" => 135
),
"Ryans" => array
(
"prestige" => 3,
"zone" => "A3D5",
"scope_frag" => 78
),
"지적인" => array
(
"prestige" => 2,
"zone" => "AE5S",
"scope_frag" => 481
)
);
foreach ($array as $group) {
$zones[$group["zone"]][] = $group["prestige"];
}
foreach ($zones as $name => $zone) {
$total = count($zone);
foreach ($zone as $prestige) {
$result[$name]["P".$prestige] += 1;
}
ksort($result[$name]);
$result[$name]["total"] = $total;
}
echo "<pre>";
print_r($result);
echo "</pre>";

Categories