I have an array like this;
$array = array(
array('id' => 1, 'amount' => 104,
array('id' => 46, 'amount' => 200,
array('id' => 1004, 'amount' => 200
);
and another array like this;
$array2 = array(
array('id' => 206, 'amount' => 50,
array('id' => 1, 'amount' => 96,
array('id' => 88, 'amount' => 2
);
How to I add check if the 'id' in array2 exists in $array. If it does at the 'amount' of $array2 to $array, if it doesn't exist append the id and amount onto the end of $array. I want the output result to look like this:
array {
[0] id = 1 amount = 200
[1] id = 46 amount = 200
[2] id = 1004 amount = 200
[3] id = 206 amount = 50
[4] id = 88 amount = 2
}
I have tried using array_merge and in_array but can't seem to get my head around it working.
You could try somthing like this :
foreach ($array as $key => $value) {
$found = false ;
foreach ($array2 as $key2 => $value2) {
if ($value2['id'] == $value['id']) {
$array2[$key2]['amount'] += $value['amount'];
$found = true;
break;
}
}
if (!$found) {
$array2[] = $value ;
}
}
print_r($array2);
outputs :
Array
(
[0] => Array
(
[id] => 206
[amount] => 50
)
[1] => Array
(
[id] => 1
[amount] => 200
)
[2] => Array
(
[id] => 88
[amount] => 2
)
[3] => Array
(
[id] => 46
[amount] => 200
)
[4] => Array
(
[id] => 1004
[amount] => 200
)
)
EDIT After comments, updated code with a final check to remove duplicated rows :
foreach ($array as $key => $value) {
$found = false ;
foreach ($array2 as $key2 => $value2) {
if ($value2['id'] == $value['id']) {
$array2[$key2]['amount'] += $value['amount'];
$found = true;
break;
}
}
if (!$found) {
$array2[] = $value ;
}
}
$final = [];
foreach ($array2 as $key1 => $value) {
$found = false ;
foreach ($final as $key2 => $value2) {
if ($value2['id'] == $value['id']) {
$final[$key2]['amount'] += $value['amount'];
$found = true;
break;
}
}
if (!$found) {
$final[] = $value ;
}
}
var_dump($final) ;
Related
i want to combine the values of array having same index name in foreach loop..
i tried array_combine but it returns the single array.
$data = $_POST['variable']; //it contain the values in an array
$result=array();
foreach ($data as $mycat){
$result = array_merge($result, $mycat);
}
echo "<pre>";print_r($result);echo "</pre>";
it returns only data in single array
Array
(
[vendor] => 1-Open Market
[priority] => 2
[demand_for_id] => 9
[ims_allocation_details_id] => 148
[temp_demand_id] => 1
)
as shown in attached picture item names are same, so when item names are same i want to combine the total values in foreach and insert only one record into database instead to two
enter image description here
the contents of $_POST['variable']; are
Array
(
[2] => Array
(
[vendor] => 1-Open Market
[temp_demand_id] => 6
[priority] => 1
[item_name] => BAJRA MOTI
[amount] => 1000
[demand_for_id] => 9
[ims_allocation_details_id] => 153
)
[1] => Array
(
[vendor] => 1-Open Market
[temp_demand_id] => 1
[priority] => 2
[item_name] => BAJRA MOTI
[amount] => 2500
[demand_for_id] => 9
[ims_allocation_details_id] => 148
)
)
You should replace
$result = array_merge($result, $mycat);
with
$result[] = array_merge($result, $mycat);
and it will not be single
UPDATE
$result = array();
foreach ($data as $mycat) {
if(!isset($result[$mycat['item_name']])) {
$result[$mycat['item_name']] = $mycat;
} else {
//do if needed
}
}
echo "<pre>";print_r($result);echo "</pre>";
You can create a custom function to solve your problem.
Example:
<?php
$array = [
[
'vendor' => '1-Open Market',
'temp_demand_id' => 6,
'priority' => 1,
'item_name' => 'BAJRA MOTI',
'amount' => 1000,
'demand_for_id' => 9,
'ims_allocation_details_id' => 153,
],
[
'vendor' => '1-Open Market',
'temp_demand_id' => 1,
'priority' => 2,
'item_name' => 'BAJRA MOTI',
'amount' => 2500,
'demand_for_id' => 9,
'ims_allocation_details_id' => 148,
],
[
'vendor' => '1-Open Market',
'temp_demand_id' => 5,
'priority' => 3,
'item_name' => 'BAJRA MOTI',
'amount' => 1000,
'demand_for_id' => 11,
'ims_allocation_details_id' => 200,
],
];
function array_merge_recursive_custom($array) {
$processed = null;
foreach ($array as &$subArray) {
if (empty($processed)) {
$processed = $subArray;
continue;
}
foreach ($subArray as $key => $value) {
if (is_numeric($value)) {
$subArray[$key] += $processed[$key];
}
}
$processed = $subArray;
}
return end($array);
}
var_dump(array_merge_recursive_custom($array));
Supposing I have this array in PHP:
Array
(
[0] => Array
(
[name] => Banana
[quantity] => 124
)
[1] => Array
(
[name] => Cherry
[quantity] => 24
)
[2] => Array
(
[name] => Apple
[quantity] => 224
)
)
How can I sum the number with the key quantity ?
Thanks.
Please, always share with us what you have tried.
It help us a lot.
You can use:
$arr = [['name' => "Banana", 'quantity' => 124], ['name' => "Cherry", 'quantity' => 24], ['name' => "Apple", 'quantity' => 224]];
$sum = 0;
foreach ($arr as $item) {
$sum += $item['quantity'];
}
Or (PHP 5.5+):
$sum = array_sum(array_column($arr, 'quantity'));
/*
Receives a Multidemensional Array (Matrix) and returns the sum of quantity.
Returns -1 on fail.
*/
function SumKeyOfArray($Matrix)
{
if(!empty($Matrix))
{
$sum = 0;
foreach($Matrix as $array)
{
if(isset($array['quantity']))
$sum = $sum + $array['quantity'];
}
return $sum;
}
return -1;
}
Another option is to use the reduce function:
$arr= [['name' => "Banana", 'quantity' => 124], ['name' => "Cherry", 'quantity' => 24], ['name' => "Apple", 'quantity' => 224]];
echo array_reduce($arr, function($sum, $elem) {
return $sum += $elem["quantity"];
});
I want to delete key [Price] but the function which I use for deletion doesn't work for this case
I have:
Array(
[Values] => 1
[Product] => Array(
[Details] => Array(
[ID] => 1
[Price] => Array(
)
)
)
)
My goal is:
Array(
[Values] => 1
[Product] => Array(
[Details] => Array(
[ID] => 1
)
)
)
I use this for removal:
function remove_key($array, $key)
{
foreach($array as $k => $v) {
if(is_array($v)) {
$array[$k] = remove_key($v, $key);
} elseif($k == $key) {
unset($array[$k]);
}
}
return $array;
}
$array = remove_key($array,'Price');
What is wrong here?
<?php
$array = Array(
'Values' => 1,
'Product' => Array(
'Details' => Array(
'id' => 1,
'Price' => Array(
)
)
)
);
unset($array['Product']['Details']['Price']);
echo "<pre>";
print_r($array);
echo "</pre>";
And the output is :
Array
(
[Values] => 1
[Product] => Array
(
[Details] => Array
(
[id] => 1
)
)
)
so if you want to fix your function you must add another condition into first if as so && $k != $key
because you are not getting into elseif and unset is not called
function remove_key($array, $key)
{
foreach($array as $k => $v) {
if(is_array($v) && $k != $key) {
$array[$k] = remove_key($v, $key);
} elseif($k == $key) {
unset($array[$k]);
}
}
return $array;
}
Here is my collected array.
$raw_ar = Array (
0 => Array ( 'ID' => 6, 'pageTitle' => 'First', 'pageContent' => 'http://localhost/cms/1', 'parentID' => 0 ),
1 => Array ( 'ID' => 7, 'pageTitle' => 'Second', 'pageContent' => 'http://localhost/cms/2', 'parentID' => 6 ),
2 => Array ( 'ID' => 8, 'pageTitle' => 'Third', 'pageContent' => 'http://localhost/cms/3', 'parentID' => 6 ) ,
3 => Array ( 'ID' => 9, 'pageTitle' => 'Four', 'pageContent' => 'http://localhost/cms/4', 'parentID' => 0 )
) ;
And my result should be like this
$final_ar = array(
0 => array ( 'ID' => 6, 'pageTitle' => 'First', 'pageContent' => 'http://localhost/cms/1', 'parentID' => 0 ,
'sub_items' => array(
0 => array('ID' => 7, 'pageTitle' =>'second', 'pageContent' => 'http://localhost/cms/2', 'parentID' => 6),
1 => array('ID' => 8, 'pageTitle' => 'Third', 'pageContent' => 'http://localhost/cms/3', 'parentID' => 6),
)
),
1 => array('ID' => 9, 'pageTitle' => 'Four', 'pageContent' => 'http://localhost/cms/4', 'parentID' => 0)
);
And here is my code
$final_ar = array();
foreach ($raw_ar as $value) {
if($value['parentID'] ==0){
$final_ar[] = $value;
}
else{
$pID = $value['parentID'];
foreach ($final_ar as $value1) {
//echo $value1['ID'].'-'.$pID;
if($value1['ID'] == $pID){
//if(isset($value1['sub_items'])){
$value1['sub_items'][] = $value;
//}else
//$value1['sub_items'] = $value;
}
$temp_ar[] = $value1;
}
$exist = 0;
foreach ($final_ar as $key => $val) {
# code...
if($val['ID'] == $temp_ar['ID']){
unset($final_ar[$key]);
$final_ar[$key] = $temp_ar;
$exist =1;
break;
}
}
if($exist == 0)
$final_arr[] = $temp_ar;
//$parent_key = array_column($raw_ar,'ID', 'parentID');
}
}
print_r($final_arr);
And I tried to code it with sub_items . But it helps to create array. But I don't know how to remove existing array once it modifies. It gives the result like this.
Array ( [0] => Array ( [0] => Array ( [ID] => 6 [pageTitle] => First [pageContent] => http://localhost/cms/1 [parentID] => 0 [sub_items] => Array ( [0] => Array ( [ID] => 7 [pageTitle] => Second [pageContent] => http://localhost/cms/2 [parentID] => 6 ) ) ) ) [1] => Array ( [0] => Array ( [ID] => 6 [pageTitle] => First [pageContent] => http://localhost/cms/1 [parentID] => 0 [sub_items] => Array ( [0] => Array ( [ID] => 7 [pageTitle] => Second [pageContent] => http://localhost/cms/2 [parentID] => 6 ) ) ) [1] => Array ( [ID] => 6 [pageTitle] => First [pageContent] => http://localhost/cms/1 [parentID] => 0 [sub_items] => Array ( [0] => Array ( [ID] => 8 [pageTitle] => Third [pageContent] => http://localhost/cms/3 [parentID] => 6 ) ) ) ) )
Try this:
function formatArray($nonFormattedArray) {
$formattedArray = [];
$subItems = [];
foreach ($nonFormattedArray as $item) {
$pid = $item['parentID'];
if ($pid != 0) {
if (isset($subItems[$pid]))
$subItems[$pid][] = $item;
else
$subItems[$pid] = [$item];
} else
$formattedArray[] = $item;
}
foreach ($formattedArray as $key => $parent) {
resolveChild($formattedArray[$key], $subItems);
}
return $formattedArray;
}
function resolveChild(&$parent, &$subItems) {
//return if no child
if (!isset($subItems[$parent['ID']]))
return $parent;
foreach ($subItems[$parent['ID']] as $key => $child) {
if (isset($parent['sub_items']))
$parent['sub_items'][] = resolveChild($subItems[$parent['ID']][$key], $subItems);
else
$parent['sub_items'] = [resolveChild($subItems[$parent['ID']][$key], $subItems)];
}
return $parent;
}
Now, formatArray($nonFormattedArray) should return your desired answer.
This will be independent of the order of your parent and child items and will reduce the total iteration count and execution time.
This will produce an Array as deep as the inheritance in the data.
Note that execution time will increase with the increment in inheritance level.
So many code you have here.
Here's my version:
foreach ($raw_ar as $value) {
if ($value['parentID'] == 0) {
$final_ar[$value['ID']] = $value;
}
}
foreach ($raw_ar as $value) {
$parent_id = $value['parentID'];
if (0 < $parent_id) {
if (!isset($final_ar[$parent_id]['sub_items'])) {
$final_ar[$parent_id]['sub_items'] = [];
}
$final_ar[$parent_id]['sub_items'][] = $value;
}
}
$final_ar = array_values($final_ar); // if you need 0-indexed array
If you're 100% sure that parent items in your array come before child ones - you can join both foreaches into one:
foreach ($raw_ar as $value) {
$parent_id = $value['parentID'];
if ($parent_id == 0) {
$final_ar[$value['ID']] = $value;
} else {
if (!isset($final_ar[$parent_id]['sub_items'])) {
$final_ar[$parent_id]['sub_items'] = [];
}
$final_ar[$parent_id]['sub_items'][] = $value;
}
}
$final_ar = array_values($final_ar); // if you need 0-indexed array
I have two multi-dimensional arrays. I need to concatenate the two without loosing any values which have the same key and different values. Here is the scenario:
Array1
(
[0] => 11
[2] => 12
[3] => 13
[4] => (
[0] => 100
[1] => 200
)
[5] => 2
[6] => 3
)
Array2
(
[0] => 11
[2] => 12
[3] => 13
[4] => (
[0] => 400
[1] => 500
)
[5] => 2
[6] => 3
)
The result should be
Result
(
[0] => 11
[2] => 12
[3] => 13
[4] => (
[0] => (
[0] => 100
[1] => 400
)
[1] => (
[0] => 200
[1] => 500
)
)
[5] => 2
[6] => 3
)
Here is one solution:
<?php
$arrayA = array(0 => 11, 2 => 12, 3 => 13, 4 => array(0 => 100, 1 => array(0 => 222),), 5 => 2, 6 => 3);
$arrayB = array(
0 => 11,
2 => 12,
3 => 13,
4 => array(
0 => 100,
1 => array(0 => array(0 => 'test1', 1 => 'test2'), 1 => array(0 => 'test1', 1 => 'test2'),),
),
5 => 2,
6 => 3
);
/**
* #param $a
* #param $b
* #return array
*/
function array_merge_graceful($a, $b)
{
$c = [];
if (is_array($a) && is_array($b)) {
foreach (array_merge(array_keys($a),array_keys($b)) as $i) {
if (!array_key_exists($i, $a)) {
$c[$i] = $b[$i];
} elseif (!array_key_exists($i, $b)) {
$c[$i] = $a[$i];
} else {
$c[$i] = array_merge_graceful($a[$i], $b[$i]);
}
}
} else {
if ($a <> $b) {
$c = [$a, $b];
} else {
$c = $a;
}
}
return $c;
}
var_dump(array_merge_graceful($arrayA, $arrayB));
?>
Try something like this
<?php
$array1 = array(11, 12, 13, array(100, 200), 2, 3);
$array2 = array(11, 12, 13, array(400, 500), 2, 3);
echo "<pre>";
print_r($array1);
print_r($array2);
$combine = array();
foreach ($array1 as $key => $value) {
if (array_key_exists($key, $combine)) {
//if is array
if (is_array($combine[$key])) {
$combine[$key] = array($combine[$key], $value);
}
} else {
$combine[$key] = $value;
}
}
foreach ($array2 as $key => $value) {
if (array_key_exists($key, $combine)) {
//if is array
if (is_array($combine[$key])) {
$combine[$key] = array($combine[$key], $value);
}
} else {
$combine[$key] = $value;
}
}
echo "<hr>";
print_r($combine);
use array_merge_recursive() function for merging arrays.For more details please refer http://php.net/manual/en/function.array-merge-recursive.php