How to find duplicate value in sample array using php
Array
(
[id] => 644
[qty] => 1
[product] => 127
[super_attribute] => Array
(
[140] => 16
)
)
Array
(
[id] => 648
[qty] => 1
[product] => 111
[super_attribute] => Array
(
[140] => 18
)
)
Array
(
[id] => 652
[qty] => 1
[product] => 111
[super_attribute] => Array
(
[140] => 18
)
)
in this above array i want to find duplicate [product] => 111 and [140] => 18 . How can i achieve this?
One possible way to do this is to combine the two elements you're looking for into one longer key, then create a two-dimensional array listing all the IDs that have the new key.
In the code below I have multiplied the product number by 1000, added the value of super_attribute[140] and cast the result to a string. There are other ways you might obtain a new key depending on what you know about the data you're working with.
<?php
$arr = [
[
"id" => 644,
"qty" => 1,
"product" => 127,
"super_attribute" => [
"140" => 16
]
],
[
"id" => 648,
"qty" => 1,
"product" => 111,
"super_attribute" => [
"140" => 18
]
],
[
"id" => 652,
"qty" => 1,
"product" => 111,
"super_attribute" => [
"140" => 18
]
]
];
$dup = [];
foreach($arr as $subArr) {
// Calculate the new combined key
$newKey = (string)($subArr['product']*10000+$subArr["super_attribute"][140]);
// If we don't have this new key, create an array with the ID,
// otherwise, add the ID to the existing array for the new key.
if (isset($dup[$newKey])) {
$dup[$newKey][] = $subArr['id'];
} else {
$dup[$newKey] = [$subArr['id']];
}
}
var_dump($dup);
Output:
array (size=2)
1270016 =>
array (size=1)
0 => int 644
1110018 =>
array (size=2) //IDs with the combined key 111 and 18
0 => int 648
1 => int 652
Related
I have following array inside foreach loop and I want to merge array value(append with comma) where "key value" (column_name,match,coll) is same/duplicate. In short I want to combine duplicate array values. How can I do this? Here is my current array
Array
(
[id] => 86
[column_name] => Accommodation
[text] => hotel
[match] => 2
[coll] => 1
)
Array
(
[id] => 87
[column_name] => Accommodation
[text] => staff
[match] => 2
[coll] => 1
)
Array
(
[id] => 91
[column_name] => Accommodation
[text] => marriot
[match] => 3
[coll] => 1
)
My expected result:
Array
(
[id] => 86
[column_name] => Accommodation
[text] => hotel staff
[match] => 2
[coll] => 1
)
Array
(
[id] => 91
[column_name] => Accommodation
[text] => marriot
[match] => 3
[coll] => 1
)
Tried with following code:
foreach ($result as $key =>$element) {
if($element['column_name'] == 'Accommodation'){
echo "<pre>";print_R($element);
}
}
For each entry generate the key (i'm using zero-characted-joined values), and fill the output array, appending text if entry with such the key already exists:
<?php
$input = [
[
'id' => 86,
'column_name' => 'Accommodation',
'text' => 'hotel',
'match' => 2,
'coll' => 1,
],
[
'id' => 87,
'column_name' => 'Accommodation',
'text' => 'staff',
'match' => 2,
'coll' => 1,
],
[
'id' => 91,
'column_name' => 'Accommodation',
'text' => 'marriot',
'match' => 3,
'coll' => 1,
],
];
$output = [];
foreach( $input as $entry ){
$key = implode("\0",[$entry['column_name'],$entry['match'],$entry['coll']]);
// No such entry yet
if( empty( $output[$key] ) )
$output[ $key ] = $entry;
// This is a duplicate, appending text
else
$output[ $key ]['text'] .= ' ' . $entry['text'];
}
print_r( array_values($output) );
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'm trying to create a "Cart" page that shows products that have been added to the cart. Currently i am displaying anything that gets added to the cart via a foreach loop that loops through an array of products. If i add the same product again, it shows twice. I'd like to remove the duplicate product and update the quantity field by 1.
For example, the products array would look like this...
[0] => Array
(
[product_id] => 222
[quantity] => 1
)
[1] => Array
(
[product_id] => 333
[quantity] => 1
)
[2] => Array
(
[product_id] => 222
[quantity] => 1
)
[3] => Array
(
[product_id] => 444
[quantity] => 1
)
[4] => Array
(
[product_id] => 222
[quantity] => 1
)
What would be the best way to remove the duplicate products that have matching product ids, and update the quantity key by 1? So product id 222 would have a quantity of 3.
With an associative array it is pretty simple:
$input = [
[
"product_id" => 222,
"quantity" => 1
],
[
"product_id" => 333,
"quantity" => 1
],
[
"product_id" => 222,
"quantity" => 1
],
[
"product_id" => 444,
"quantity" => 1
],
[
"product_id" => 222,
"quantity" => 1
]
];
$output = [];
foreach($input as $row) {
if (array_key_exists($row["product_id"], $output)) {
$output[$row["product_id"]]["quantity"] += $row["quantity"];
}
else {
$output[$row["product_id"]] = [
"quantity" => $row["quantity"]
];
}
}
var_dump($output);
I want to remove duplicate record which is highest value in array.
Array :
Array
(
[0] => Array
(
[id] => 1
[number] => 123
[price] => 6
)
[1] => Array
(
[id] => 2
[number] => 456
[price] => 6
)
[2] => Array
(
[id] => 3
[number] => 123
[price] => 5
)
)
Expected Result :
Array
(
[0] => Array
(
[id] => 2
[number] => 456
[price] => 6
)
[1] => Array
(
[id] => 3
[number] => 123
[price] => 5
)
)
number is duplicate field and after that need to compare price. Which will be lower that will be display. Rest of all should be removed.
What I tried :
$lowest = min($myArray);
$result = array_filter($myArray, function($value, $key) use ($lowest) {
return $value === $lowest;
}, ARRAY_FILTER_USE_BOTH);
How can i do that?
UPDATE :
#Daniel Dez solution is almost working. I used 3rd solution of him. But, It should be working like this.
For ex : number 123 is duplicate records now it's lowest price is 2. Then, it should be display rest of 123 number's array element remove.
Array :
$data = [
[
"id" => 1,
"number" => 123,
"price" => 2,
],
[
"id" => 2,
"number" => 456,
"price" => 6,
],
[
"id" => 3,
"number" => 123,
"price" => 5,
],
[
"id" => 4,
"number" => 123,
"price" => 11,
],
[
"id" => 5,
"number" => 456,
"price" => 5,
],
[
"id" => 6,
"number" => 123,
"price" => 5,
]
];
Expected Output :
Array
(
[0] => Array
(
[id] => 1
[number] => 123
[price] => 2
)
[1] => Array
(
[id] => 2
[number] => 456
[price] => 5
)
)
please help me.
Thanks.
Data:
$numbers = array_unique(array_column($data, 'number'));
usort($data, function ($a, $b) {
return $a['price'] - $b['price'];
});
$result = [];
foreach ($numbers as $number) {
foreach ($data as $item) {
if ($item['number'] == $number) {
break;
}
}
$result[] = $item;
}
print_r($result);
my collection of data in array which is shown below the index key is A,B,C but i want to store these key in "key" and its key letter's words in "dishes" key
array:3 [
"A" => array:4 [
0 => 37
1 => "Algerian"
2 => 6
3 => "American"
]
"B" => array:6 [
0 => 27
1 => "Belgian"
2 => 20
3 => "Brazilian"
]
and so on..
i wanna sort this array like aplhabetic order as shown below
array:10 [
0 => array:2 [
"key" => "A"
"dishes" => array:2 [
0=>array:2[
"id" => 37
"type" => "Algerian"
],
1=>array:2[
"id" => 6
"type" => "American"
]
]
]
1 => array:2 [
"key" => "B"
"dishes" => array:2 [
0=>array:2[
"id" => 27
"type" => "Belgian"
],
1=>array:2[
"id" => 20
"type" => "Brazilian"
]
]
]
and so on...
This would be a possible solution:
<?php
$input = [
'A' => [
0 => 37,
1 => "Algerian",
2 => 6,
3 => "American"
],
'B' => [
0 => 27,
1 => "Belgian",
2 => 20,
3 => "Brazilian"
]
];
$output = [];
array_walk($input, function($values, $key) use (&$output) {
$entry = [
'key' => $key,
'dishes' => []
];
foreach(array_chunk($values, 2) as $chunk) {
$entry['dishes'][] = [
'id' => $chunk[0],
'type' => $chunk[1]
];
}
$output[] = $entry;
});
print_r($output);
The output of above code obviously is:
Array
(
[0] => Array
(
[key] => A
[dishes] => Array
(
[0] => Array
(
[id] => 37
[type] => Algerian
)
[1] => Array
(
[id] => 6
[type] => American
)
)
)
[1] => Array
(
[key] => B
[dishes] => Array
(
[0] => Array
(
[id] => 27
[type] => Belgian
)
[1] => Array
(
[id] => 20
[type] => Brazilian
)
)
)
)
You have to loop through the original array to create your new structure. Then you can use the ksort function to sort them.
$newArr = new array();
for ($arr as $elem) {
$dishArr = new array();
for($elem['dishes'] as $dish) {
$dishArr[] = $dish['id'];
$dishArr[] = $dish['type'];
}
$newArr[$elem['key']] = $dishArr;
}
ksort($newArr);