My Array is below
$sample_arr = Array
(
[0] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[1] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 20
[ref] => ref 2
)
[2] => Array
(
[index] => 2
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 21
[ref] => ref 2
)
)
As you can see in the above array there is article_Id twice in the array with value 6
I would like to find the details of the second row so that I can make the second row qty 41 i.e my result array will be like the one below
I have tried the in_array function but still there is something missing
I also tried with the foreach but the problem is that how to get the first appearance row qty? i.e in the $sample_arr when the user adds the third record with article_Id 6 the second row must be updated as shown below
$result_arr = Array
(
[0] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[1] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 41
[ref] => ref goes here
)
)
Looks like article ID is unique. So, we can kep storing data in this $newArray variable with the key as article ID.
Every time, it's checked if a record containing the article id exists. If so, the quantity is added. If not, it's appended to the $newArray.
$newArray = array();
foreach($sample_arr as $arr) {
if (isset($newArray[$arr['article_Id']])) {
$newArray[$arr['article_Id']]['qty'] += $arr['qty'];
$newArray[$arr['article_Id']]['ref'] = 'Ref goes here'; // If this the string that replaces the ref
} else {
$newArray[$arr['article_Id']] = $arr;
}
}
$newArray = array_values($newArray);
Output:
Array
(
[0] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[1] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 41
[ref] => ref 2
)
)
Try the following:
$new_merged_array = array();
if(!empty($sample_arr )){
foreach($sample_arr as $sample_ar){
if(!empty($sample_ar) && isset($sample_ar['article_Id'])){
if(isset($new_merged_array[$sample_ar['article_Id']])){
$new_merged_array[$sample_ar['article_Id']]['qty'] += $sample_ar['qty'];
}else{
$new_merged_array[$sample_ar['article_Id']] = $sample_ar;
}
}
}
}
print_r($new_merged_array);
Output will be:
Array(
[4] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[6] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 41
[ref] => ref 2
)
)
Another way:
$new_merged_array = $sample_array = array();
if(!empty($sample_arr )){
foreach($sample_arr as $sample_ar){
if(!empty($sample_ar) && isset($sample_ar['article_Id'])){
if(isset($new_merged_array[$sample_ar['article_Id']])){
$new_merged_array[$sample_ar['article_Id']]['qty'] += $sample_ar['qty'];
}else{
$new_merged_array[$sample_ar['article_Id']] = $sample_ar;
}
}
}
}
if(!empty($new_merged_array )){
foreach($new_merged_array as $new_merged_arr){
$sample_array[] = $new_merged_arr;
}
}
print_r($sample_array);
Output will be:
Array(
[0] => Array
(
[index] => 0
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 4
[qty] => 50
[ref] => ref
)
[1] => Array
(
[index] => 1
[in_id] => 309
[date] => 2016-08-01
[article_Id] => 6
[qty] => 41
[ref] => ref 2
)
)
$sample_arr = array
(
0 => array
(
'index'=> 0,
'in_id' => 309,
'date' => '2016-08-01',
'article_Id' => 4,
'qty' => 50,
'ref' => 'ref'
),
1 => array
(
'index' => 1,
'in_id' => 309,
'date' => '2016-08-01',
'article_Id' => 6,
'qty' => 20,
'ref' => 'ref 2'
),
2 => array
(
'index' => 2,
'in_id' => 309,
'date' => '2016-08-01',
'article_Id' => 6,
'qty' => 21,
'ref' => 'ref 2'
)
);
$articleArray = [];
foreach($sample_arr as $key=>$value){
$articleId = $value['article_Id'];
if(array_key_exists($articleId,$articleArray)){
$articleArray[$articleId]['qty'] = $articleArray[$articleId]['qty'] + $value['qty'];
}else{
$articleArray[$articleId] = $value;
}
}
$articleArray = array_values($articleArray);
print_r($sample_arr);
print_r($articleArray);
Demo
in_array() does not work on multidimensional arrays. You could write a recursive function to do that for you:
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
Usage:
$b = array(array("Mac", "NT"), array("Irix", "Linux"));
echo in_array_r("Irix", $b) ? 'found' : 'not found';
Related
I have two array with different fields, first array is user information and second is users coupon number.
I want total = (coupon_cnt * 1000) + liked_cnt if two array id 's equal
I wrote this code but this wont return user info
$input = array($like , $coupon);
foreach ($input as $set) {
array_walk($set, function($entry) use (&$output) {
$count = array_pop($entry);
$id = array_pop($entry);
if (array_key_exists($id, $output)) {
$output[$id]['user_score'] += 1000 * $count;
} else {
$output[$id] = ['id' => $id, 'user_score' => $count];
}
});
}
$score = array_values($output);
Arrays
$like = Array
(
[0] => Array
(
[id] => 85
[user_phone] => 00000000
[user_email] => test#gmail.com
[user_name] => test
[user_password] => test
[user_city] => 1
[user_picture] => V5XgNt6P3BhT9iucdv_photo_001.jp
[user_coupon_token] => 43131
[user_post_hour] => 10
[user_is_block] => 0
[user_reg_date] => 2017-05-16 13:52:35
[last_ip] =>
[user_push_token] =>
[liked_cnt] => 6 <-- I want add this to coupon_cnt * 1000
)
)
$coupon = Array
(
[0] => Array
(
[id] => 85
[coupon_cnt] => 2
)
[1] => Array
(
[id] => 86
[coupon_cnt] => 1
)
[2] => Array
(
[id] => 139
[coupon_cnt] => 1
)
)
output
$output = Array
(
[0] => Array
(
[id] => 85
[user_phone] => 00000000
[user_email] => test#gmail.com
[user_name] => test
[user_password] => test
[user_city] => 1
[user_picture] => V5XgNt6P3BhT9iucdv_photo_001.jp
[user_coupon_token] => 43131
[user_post_hour] => 10
[user_is_block] => 0
[user_reg_date] => 2017-05-16 13:52:35
[last_ip] =>
[user_push_token] =>
[output] => 2006 <-- I want this
)
)
anyone can help?
First make the 2nd array a bit easier to manage:
$easierToManageSecondArray = array_column($coupon, "coupon_cnt", "id");
Then the "loop":
$like = array_map(function ($value) use ($easierToManageSecondArray) {
if (isset($easierToManageSecondArray[$value["id"]]) {
$value["user_score"] = ($easierToManageSecondArray[$value["id"]] * 1000) + $value["liked_cnt"];
} else {
$value["user_score"] = $value["liked_cnt"]; //No idea if this makes sense.
}
return $value;
}, $like);
Check below code:
$like = Array
(
0 => Array
(
'id' => 85,
'user_phone' =>' 00000000',
'user_email' => 'test#gmail.com',
'user_name' => 'test',
'user_password' => 'test',
'liked_cnt' => 6
)
);
$coupon = Array
(
0 => Array
(
'id' => 85,
'coupon_cnt' => 2
),
1 => Array
(
'id' => 86,
'coupon_cnt' => 1
)
);
foreach($like as $key => $value){
foreach($coupon as $value2){
if($value['id'] === $value2['id']){
$like[$key]['liked_cnt'] += $value2['coupon_cnt'] * 1000;
}
}
}
print_r($like);
Output
Array
(
[0] => Array
(
[id] => 85
[user_phone] => 00000000
[user_email] => test#gmail.com
[user_name] => test
[user_password] => test
[liked_cnt] => 2006
)
)
Demo : Click Here
Please Help! I want to validate array with duplicate sub-array values. I have an multi-dimensional array. I want to return keys of sub-array with duplicate product_id value. Example: In my array, I have sub-array with duplicate product_id = 124. I want to return their key.
[purchase_order_products] => Array
(
[0] => Array
(
[product_id] => 124
[barcode] => 480001407081
[item_code] =>
[name] => Brew Kettle Can 330mL
[qty] =>
[unit] => 2
[pcs_have] => 1
[total_pcs] => 1
[cost] => 34.83
[total_item_price] => 34.83
[stocks] =>
[po_qty] =>
)
[1] => Array
(
[product_id] => 125
[barcode] => 480001416108
[item_code] =>
[name] => Colt 45 Can 330mL
[qty] =>
[unit] => 2
[pcs_have] => 1
[total_pcs] => 1
[cost] => 29.58
[total_item_price] => 29.58
[stocks] =>
[po_qty] =>
)
[2] => Array
(
[product_id] => 124
[barcode] => 480001407081
[item_code] =>
[name] => Brew Kettle Can 330mL
[qty] =>
[unit] => 2
[pcs_have] => 1
[total_pcs] => 1
[cost] => 34.83
[total_item_price] => 34.83
[stocks] =>
[po_qty] =>
)
)
The output I want is:
Array(0,2)
Edit: I've updated the answer quite a bit.
Edit 2: Now utilizing the built in array functions to find the duplicates
$products = [
0 => ['product-id' => 124],
1 => ['product-id' => 125],
2 => ['product-id' => 124],
3 => ['product-id' => 126],
4 => ['product-id' => 126],
8 => ['product-id' => 124],
];
// Find the duplicates
$product_ids = array_column($products, 'product-id');
$count = array_count_values($product_ids);
$duplicates = array_filter($count, function($var) {
return $var > 1;
});
// List all the entries with duplicate ids:
foreach ( array_flip($duplicates) as $product_id ) {
$filter = array_filter($products, function($var) use ($product_id) {
return ( $var['product-id'] === $product_id );
});
print_r('Product-id: ' . $product_id . ' is duplicated in entries: ');
print_r(array_keys($filter));
}
The output:
// Product-id: 124 is duplicated in entries: Array
// (
// [0] => 0
// [1] => 2
// [2] => 8
// )
// Product-id: 126 is duplicated in entries: Array
// (
// [0] => 3
// [1] => 4
// )
Use this code to get key for duplicate product id:
$products = $array['purchase_order_products'];
$duplicate_products_keys = array();
$products_ids = array();
foreach($products as $key => $product) {
if(in_array($product['product_id'], $products_ids)) {
$duplicate_products_keys[] = $key;
}
$products_ids[$product['product_id']] = $product['product_id'];
}
prinr_r($duplicate_products_keys);
How do you filter this multidimensional array with array_filter() based on [channel]?
Array
(
[0] => Array
(
[268a9d2d25fc2b9765c7cd7b8a768d3e] => Array
(
[dj_name] => Emilian
[show_name] => TechnoShow
[channel] => techno
[show_image] => http://www.digitalark.ro/dieselfm/wp-content/uploads/2016/01/avatar.jpg
[time] => 0
[time_end] => 1
[sun1] => 1
[sun2] => 1
[sun3] => 1
[sun4] => 1
[sun5] => 1
)
)
[1] => Array
(
[e13268de7c56db42f8aeab2ab4c607f2] => Array
(
[dj_name] => John Doe
[show_name] => John Doe`s Trance Show
[channel] => trance
[show_image] => http://www.digitalark.ro/dieselfm/wp-content/uploads/2016/01/dummy.jpg
[time] => 11
[time_end] => 11
[mon1] => 1
[mon2] => 1
[tue2] => 1
[mon3] => 1
[fri3] => 1
[mon4] => 1
[mon5] => 1
)
)
)
Results should have only the arrays that have the value "techno", for example:
Array
(
[0] => Array
(
[268a9d2d25fc2b9765c7cd7b8a768d3e] => Array
(
[dj_name] => Emilian
[show_name] => TechnoShow
[channel] => techno
[show_image] => http://www.digitalark.ro/dieselfm/wp-content/uploads/2016/01/avatar.jpg
[time] => 0
[time_end] => 1
[sun1] => 1
[sun2] => 1
[sun3] => 1
[sun4] => 1
[sun5] => 1
)
))
I have tried using:
$data = array_filter($dataraw, function($fs) use ($genre) {return $fs['channel'] == $genre});
EDIT:
$djs = get_posts($args);
foreach ($djs as $dj) {
$temp = maybe_unserialize(get_post_meta($dj->ID, 'show_data',true));
if ($temp) $show_data[] = maybe_unserialize(get_post_meta($dj->ID, 'show_data',true));
}
$datax = array_filter($show_data, function($fs) use ($genre) {
return array_values($fs)[0]['channel'] == $genre;
});
print_r($datax);
I'll assume the parse error in your code was a copy/paste mistake. The problem is that the element passed into the function is a deeper array. Try:
return current($fs)['channel'] === $genre;
Also you might want to use === so the results are as expected.
I have a problem with my sum of arrays. So I have this array :
Array
(
[0] => Array
(
[totalGames] => 21
[nature] => 542
)
[1] => Array
(
[totalGames] => 2
[nature] => 418
)
[2] => Array
(
[totalGames] => 26
[nature] => 728
)
[3] => Array
(
[totalGames] => 3
[nature] => 542
)
[4] => Array
(
[totalGames] => 2
[nature] => 418
)
)
I want to make a sum of this array to get this result :
Array
(
[0] => Array
(
[totalGames] => 24
[nature] => 542
)
[1] => Array
(
[totalGames] => 4
[nature] => 418
)
[2] => Array
(
[totalGames] => 26
[nature] => 728
)
)
I tried like this :
while ($aRecord = $rResult->fetch_array(MYSQLI_ASSOC))
{
if($aData['nature'] == $aRecord['nature']){
$aData[] = $aRecord;
}else{
$aData['nature'] = $aRecord['nature'];
$aData['totalGames'] += $aRecord['nature']['totalGames'];
}
}
But not work. What I'm doing wrong ? Can you help me please ? Thx in advance and sorry for my english.
I also tried but it did not work :
SELECT COUNT(*) as totalGames, nature FROM master WHERE date(date)="2015-11-20" GROUP BY nature ORDER by totalGames
Your code should be:
$myArr = array(array('totalGames' => 21, 'nature' => 542),array('totalGames' => 2,'nature' => 418),array('totalGames' => 26,'nature' => 728), array('totalGames' => 3,'nature' => 542),array('totalGames' => 2,'nature' => 418));
$sum = array_reduce($myArr, function ($a, $b) {
isset($a[$b['nature']]) ? $a[$b['nature']]['totalGames'] += $b['totalGames'] : $a[$b['nature']] = $b;
return $a;
});
print_r($sum);
Try as
while ($aRecord = $rResult->fetch_array(MYSQLI_ASSOC)){
$hash = $aRecord['nature'];
if(isset($aData[$hash])){
$aData[$hash]['totalGames'] += $aRecord['totalGames'];
}else{
$aData[$hash]['nature'] = $aRecord['nature'];
$aData[$hash]['totalGames'] = $aRecord['totalGames'];
}
}
I have an array in which i want only lineNo and Isdirty field in each array .
My demo code is
Array
(
[CodeConfiguration] => Array
(
[0] => Array
(
[ObjectType] => 12
[LineNo] => 1
[CompanyID] => 1
[BranchID] => 46
[ModifiedDate] => 2014-04-25 05:10:15
[RevisionNumber] => 6
[IsDirty] =>
)
)
[TaxConfiguration] => Array
(
[0] => Array
(
[LineNo] => 2
[IsDirty] => 1
[ItemGroupID] =>
[TaxID] =>
[CalculationType_080] => 430
[RevisionNumber] => 1
)
[1] => Array
(
[LineNo] => 1
[IsDirty] => 1
[ItemGroupID] =>
[TaxID] =>
[CalculationType_080] => 372
[RevisionNumber] => 1
)
)
)
Only LineNo And Isdirty field want in every index array .So please suggest me solution.
You can sue following;
$finalArr = array();
foreach ($arr as $key => $item) {
foreach ($item as $k => $v) {
$finalArr[$key][] = array(
"LineNo" => $v["LineNo"],
"IsDirty" => $v["IsDirty"]
);
}
}
Here is a working demo: Demo