Merge duplicates in array PHP [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I have an array generated daily that will have duplicate products in it.
[0] => Array
(
[product_id] => 85
[name] => Widescreen Espresso v6.1
[quantity] => 1
)
[1] => Array
(
[product_id] => 85
[name] => Widescreen Espresso v6.1
[quantity] => 2
)
[2] => Array
(
[product_id] => 114
[name] => Panama Esmerelda Diamond Mountain
[quantity] => 1
)
I want to find duplicate products and total them up in an array that would look like this:
[0] => Array
(
[product_id] => 85
[name] => Widescreen Espresso v6.1
[quantity] => 3
)
[1] => Array
(
[product_id] => 114
[name] => Panama Esmerelda Diamond Mountain
[quantity] => 1
)
UPDATE:
I didn't want to remove the duplicates I want to merge duplicates so that the quantity of the product is added together. I managed to work a solution to it with the help of Meenesh Jain's answer below.
$final_array = array();
foreach($order_data as $item => $item_value) {
$pid = $item_value['product_id'];
if(!isset($final_array[$pid])) {
$final_array[$pid] = $item_value;
} else {
$final_array[$pid]['quantity'] += $item_value['quantity'];
}
}
print_r(array_values($final_array));

You can do it with mysqli
OR
you can apply a custom method on your array
$temp_array = $new_array = array();
foreach($array as $key => $arr_values){
if(!in_array($arr_values['product_id'], $temp_array)){
array_push($temp_array, $arr_values['product_id']);
array_push($new_array,$array[$key]);
}
}
// this code will do the trick

My try:
function newArray($oldarray){
$newarray;
$newarray[0] = $oldarray[0];
$ids;
$ids[0] = array($oldarray[0][product_id],0);
for($i = 1; $i < count($oldarray);$i++){
$add = true;
for($x = 0; $x < count($ids);$x++){
if($oldarray[$i][product_id] == $ids[$x][0]){
$add = false;
$newarray[$ids[$x][1]-1] = array($newarray[$ids[$x][1]-1][product_id],$newarray[$ids[$x][1]-1][name],$newarray[$ids[$x][1]-1][quantity]+$oldarray[$i][quantity]);
}
}
if($add == true){
$newarray[count($newarray)] = $oldarray[$i];
$ids[count($ids)] = array($oldarray[$i][product_id],count($newarray));
}
}
return $newarray;
}

You need to use this function (need to pass $array=name of array and $key as 'product_id'):
function super_unique($array,$key)
{
$temp_array = array();
foreach ($array as &$v) {
if (!isset($temp_array[$v[$key]]))
$temp_array[$v[$key]] =& $v;
}
$array = array_values($temp_array);
return $array;
}
Example :
<?php
$vikas=array('0' => array
(
'product_id' => 85,
'name' => "Widescreen Espresso v6.1",
'quantity' => 1
),
'1' => array
(
'product_id' => 85,
'name' => "Widescreen Espresso v6.1",
'quantity' => 2
),
'2' => array
(
'product_id' => 114,
'name' => "Panama Esmerelda Diamond Mountain",
"quantity" => 1
)
);
function super_unique($array,$key)
{
$temp_array = array();
foreach ($array as &$v) {
if (!isset($temp_array[$v[$key]]))
$temp_array[$v[$key]] =& $v;
}
$array = array_values($temp_array);
return $array;
}
//print_r(array_unique($vikas['product_id']));
$vik=super_unique($vikas,'product_id');
print_r($vik);
?>

Related

PHP Array Readable [closed]

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 6 years ago.
Improve this question
I have an Array format.
Array
(
[0] => Array
(
[order_id] => 1
)
[1] => Array
(
[order_id] => 11
)
[2] => Array
(
[order_id] => 12
)
)
It should to be changed the array format to be like this format:
[1,11,12];
Please help. Thank you in advanced.
For (PHP 5 >= 5.5.0, PHP 7) you can use array_column and lower than that you can use array_map function (for PHP < 5.3) you need to define saperate function for array_map instead of anonymous function.
$array = array
(
'0' => array
(
'order_id' => 1
),
'1' => array
(
'order_id' => 11
),
'2' => array
(
'order_id' => 12
)
);
$new_array = array_column($array, 'order_id');
print_r($new_array);
$new_array = array_map(function($element) {
return $element['order_id'];
}, $array);
print_r($new_array);
output
Array
(
[0] => 1
[1] => 11
[2] => 12
)
How about this?
$arr = Array
(
0 => Array
(
'order_id' => 1
),
1 => Array
(
'order_id'=> 11
),
2 => Array
(
'order_id' => 12
),
);
$newArr = array();
foreach($arr as $x){
foreach($x as $y){
$newArr[] = $y;
}
}
You can try this:
$ar = array(array('order_id' => 1), array('order_id' => 11), array('order_id' => 12));
$temp = array();
foreach ($ar as $val) {
$temp[] = $val['order_id'];
}
print_r($temp);
Basically, you are looking to flatten the array. This SO answer has some tips on how to do that. Also, there's a golf version in this Github gist.
For the specific case in your question, this should do
function specificFlatten($arr) {
if (!is_array($arr)) return false;
$result = [];
foreach ($arr as $arr_1) {
result[] = $arr_1['order_id'];
}
return $result;
}

PHP - Convert a Single Array into a Multidimensional Array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm newbie in PHP.
I need send data for API purpose.
I have array print_r($detail) like this
Array
(
[0] => Array
(
[id] => item1
)
[1] => Array
(
[price] => 300
)
[2] => Array
(
[quantity] => 1
)
[3] => Array
(
[id] => item2
)
[4] => Array
(
[price] => 400
)
[5] => Array
(
[quantity] => 2
)
)
And I want convert it to multidimensional before sending to another process, like
Array
(
[0] => Array
(
[id] => item1
[price] => 300
[quantity] => 1
)
[1] => Array
(
[id] => item2
[price] => 400
[quantity] => 2
)
)
How it is possible?
You can split your $details array into multiple chunks. I've written the following function which accepts a custom chunk size (note count($initialArray) % $chunkSize === 0 must be true):
function transformArray(array $initialArray, $chunkSize = 3) {
if (count($initialArray) % $chunkSize != 0) {
throw new \Exception('The length of $initialArray must be divisible by ' . $chunkSize);
}
$chunks = array_chunk($initialArray, 3);
$result = [];
foreach ($chunks as $chunk) {
$newItem = [];
foreach ($chunk as $item) {
$newItem[array_keys($item)[0]] = reset($item);
}
$result[] = $newItem;
}
return $result;
}
Given your details array, calling transformArray($details) will result in:
The customizable chunk size allows you to add more data to your source array:
$details = [
['id' => 'item1'],
['price' => 300],
['quantity' => 1],
['anotherProp' => 'some value'],
['id' => 'item2'],
['price' => 400],
['quantity' => 2],
['anotherProp' => 'another value'],
];
The function call is now transformArray($details, 4);:
This version may be with the same result of #PHPglue answer. But this takes only one foreach. I think this is faster, more efficient way as stated here by one of the Top SO Users.
Try to look if you want it.
Live Demo
<?php
function explodeArray($arr)
{
$newArr = array();
foreach($arr as $row)
{
$key = array_keys($row)[0];
$curArr = count($newArr) > 0 ? $newArr[count($newArr)-1] : array();
if( array_key_exists($key, $curArr) )
{
array_push($newArr, array($key=>$row[$key]) );
}
else
{
$index = count($newArr) > 0 ? count($newArr) - 1 : 0 ;
$newArr[$index][$key] = $row[$key];
}
}
return $newArr;
}
Different Arrays for testing.
$detail = array(
array('id'=>'item1'),
array('price'=>300),
array('quantity'=>1),
array('id'=>'item2'),
array('price'=>400),
array('quantity'=>2)
);
var_dump( explodeArray($detail) );
$detail_match = array(
array('id'=>'item1'),
array('price'=>300),
array('quantity'=>1),
array('newkey'=>'sample'),
array('id'=>'item2'),
array('price'=>400),
array('quantity'=>2),
array('newkey'=>'sample')
);
var_dump( explodeArray($detail_match) ); // Works with any size of keys.
$detail_diff_key = array(
array('id'=>'item1'),
array('price'=>300),
array('quantity'=>1),
array('diff1'=>'sample1'),
array('id'=>'item2'),
array('price'=>400),
array('quantity'=>2),
array('diff2'=>'sample2')
);
var_dump( explodeArray($detail_diff_key) ); // Works with any size of keys and different keys.
$detail_unmatch = array(
array('id'=>'item1'),
array('price'=>300),
array('quantity'=>1),
array('unmatchnum'=>'sample1'),
array('id'=>'item2'),
array('price'=>400),
array('quantity'=>2)
);
var_dump( explodeArray($detail_unmatch) );
I think this little block of code work for you.
Use:
$detail = array(
"0" => array("id" => "item1"),
"1" => array("price" => "300"),
"2" => array("quantity" => "1"),
"3" => array("id" => "item2"),
"4" => array("price" => "400"),
"5" => array("quantity" => "2"),
"6" => array("id" => "item3"),
"7" => array("price" => "500"),
"8" => array("quantity" => "3")
);
$i = 0;
$j = 0;
$multi_details = array();
while($j < count($detail)){
$multi_details[$i][id] = $detail[$j++][id];
$multi_details[$i][price] = $detail[$j++][price];
$multi_details[$i][quantity] = $detail[$j++][quantity];
$i++;
}
echo '<pre>';
print_r($multi_details);
echo '</pre>';
Output:
Array
(
[0] => Array
(
[id] => item1
[price] => 300
[quantity] => 1
)
[1] => Array
(
[id] => item2
[price] => 400
[quantity] => 2
)
[2] => Array
(
[id] => item3
[price] => 500
[quantity] => 3
)
)
Something like this should do it
$newArray = array();
$newRow = array();
foreach ($array as $row) {
$key = array_keys($row)[0];
$value = array_values($row)[0];
if ($key == 'id') {
$newArray[] = $newRow;
}
$newRow[$key] = $value;
}
$newArray[] = $newRow;
This version looks for repeat keys then creates a new Array whenever they are the same so you could have some different data. Hope it helps.
function customMulti($customArray){
$a = array(); $n = -1; $d;
foreach($customArray as $i => $c){
foreach($c as $k => $v){
if(!isset($d)){
$d = $k;
}
if($k === $d){
$a[++$n] = array();
}
$a[$n][$k] = $v;
}
}
return $a;
}
$wow = customMulti(array(array('id'=>'item1'),array('price'=>300),array('quantity'=>1),array('id'=>'item2'),array('price'=>400),array('quantity'=>2)));
print_r($wow);

How to merge values in foreach loop php

I am working in multidimensional array, i have an array like this and i want to merge array
[0] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19
[productId] => 50
)
[1] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 20
[productId] => 50
)
All i need is to make array by join orderId 19,20
ie,
[0] => Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19,20
[productId] => 50
)
I want to arrange like this.please help me to achieve this
You can try something like this
//This is your old array that you describe in your first code sample
$old_array = array();
// This will be the new joined array
$new = array();
// This will hold the key-pairs for each array within your initial array
$temp = array();
// This will hold all the values of orderId
$orderId = array();
// Loop through each first-level array with the original array
foreach($old_array as $val) {
//Loop through each second-level array
foreach($val as $key => $value) {
// Set the key-pair values in the $temp array
$temp[$key] = $temp[$value];
if($key == "orderId") {
// Add the current orderId value to the orderId array
array_push($orderId,$value);
// Join all the orderId values into the $temp array
$temp[$key] = join(",", $orderId);
}
}
}
//Push the final values to the new array to get a 2 dimensional array
array_push($new, $temp);
Note: I did not test any of the following code so it is very likely to not work at first.
This is also VERY bad array design and there are more likely easier and more practical solutions to this problem, but you will need to give more details on what you want to achieve
$original_array = array(); //this is the array you presented
$new_array = array(); //this is the output array
foreach($original_array as $arr) {
foreach($arr as $key => $value) {
if(array_key_exists($key, $new_array)) { //if you already assigned this key, just concat
$new_array[0][$key] .= "," . $value;
} else { //otherwise assign it to the new array
$new_array[0][$key] = $value;
}
}
}
It will give you the desired result
$arrNew = array();
$i = 0;
foreach($multiDArray as $array)
{
foreach($array as $key=>$value)
{
if($i > 0)
{
if($arrNew[$key] != $value)
{
$str = $arrNew[$key].','.$value;
$arrNew[$key] = $str;
}
}
else
{
$arrNew[$key] = $value;
}
}
$i++;
}
print_r($arrNew);
Result:
Array
(
[QuizId] => 173
[QuizName] => Reprocessing Surgical Drapes and Gowns
[totalexams] => 1
[UserScore] => 8
[MaxScore] => 20
[passed] => 1
[CategoryId] => 1
[CategoryName] => CRCST
[totalTimes] => 1
[orderId] => 19,20
[productId] => 1
)

PHP Retrieve minimum values in a 2D associative array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have the below array:
Array
(
[0] => Array
(
[id] => 1
[price1] => 16
[price2] => 10
[price3] => 3
)
[1] => Array
(
[id] => 2
[price1] => 19
[price2] => 2
[price3] => 6
)
[2] => Array
(
[id] => 3
[price1] => 14
[price2] => 32
[price3] => 1
)
)
I want to get the lower price from each row independent from the other rows. for example for id=1 the lower price is 3 and for id=2 the lower is 2 and so on. Any idea how to automate this.
Possible solution:
Demo
foreach($array as $item)
{
$lowestKey = '';
foreach($item as $key => $value)
{
if(strpos($key, 'price') === 0)
{
if($lowestKey == '')
{
$lowestKey = $key;
}
else
{
if($value < $item[$lowestKey])
{
$lowestKey = $key;
}
}
}
}
echo 'lowest for id ' . $item['id'] . ': ' . $item[$lowestKey];
}
The benefits of this method are:
The price keys don't have to be consecutive, or even numerical. Any key that begins with price is treated as a price.
There can be unlimited prices, it's not restricted to three.
Any other data stored in the array won't affect it or break anything. So for example if in future you added a description key, it won't affect the code or require any modifications.
Try this:
$newarray = array();
foreach ($array as $row)
{
$id = $row['id'];
unset($row['id']);
$newarray[$id] = min($row);
}
There you go. $newarray now contains the id => {lowest value} of each row.
$r = array_reduce($array, function(&$result, $item) {
$key = $item['id'];
unset($item['id']);
$result[$key] = min($item);
return $result;
});
Try the below:
$prices = array(0 => array ( 'id' => 1,
'price1' => 16,
'price2' => 10,
'price3' => 3
),
1 => array ( 'id' => 2,
'price1' => 19,
'price2' => 2,
'price3' => 6
),
2 => array ( 'id' => 3,
'price1' => 14,
'price2' => 32,
'price3' => 1
)
);
foreach($prices as $price) {
$tmp_arr = array(0=> $price['price1'], 1=> $price['price2'], 2=> $price['price3']);
sort($tmp_arr);
$arr_low_price = array('id'=> $price['id'], 'low_price' => $tmp_arr[0]);
print_r($arr_low_price);
echo '<br />';
}
Try may help:
$price = array();
foreach( $array as $key=>$each ){
$low = $each['price1'];
if( $each['price2'] < $low ){
$low = $each['price2'];
}
if( $each['price3'] < $low ){
$low = $each['price3'];
}
$price[$key] = $low;
}
print_r( $price );

How to get value from multidimensional array value

Array
(
[updateCategories] => Array
(
[products] => Array
(
[0] => Array
(
[cat_id] => 3
[position] => 2
[product_id] => 8
)
[1] => Array
(
[cat_id] => 4
[position] => 11
[product_id] => 8
)
[2] => Array
(
[cat_id] => 3
[position] => 4
[product_id] => 39
)
[3] => Array
(
[cat_id] => 4
[position] => 9
[product_id] => 8
)
[4] => Array
(
[cat_id] => 3
[position] => 6
[product_id] => 41
)
[5] => Array
(
[cat_id] => 11
[position] => 7
[product_id] => 8
)
The above array is my output array but I need to get all cat_id of product_id=8. How can I do this?
$newarr = array();
foreach( $arr['updateCategories']['products'] as $myarr)
{
if($myarr['product_id'] == 8)
$newarr[] = $myarr['cat_id'];
}
The simpliest solution is
$result = array();
foreach($yourArray['updateCategories']['products'] as $product)
if($product['product_id] == 8)
$product[] = $product['cat_id'];
where $yourArray is the array which dump you have published.
Try something like this:
$arr = array();
foreach ($products as $key => $value)
{
if($value['product_id'] == 8)
{
$arr[] = $key;
}
}
print_r($arr); // <-- this should output the array of products with key as 8
Use this
foreach($array['updateCategories']['products'] as $product) {
if(isset($product['product_id']) && $product['product_id']==8) {
//do anything you want i am echoing
echo $product['cat_id'];
}
}
You can use array_filter.
function filterProducts($product) {
return ($product['product_id'] == 8);
}
$myProducts = array_filter(
$myArray['updateCategories']['products'],
'filterProducts'
);
Where $myArray is the array displayed in your post.
Can handle this by doing something like this
$matching_products = array();
foreach ($products as $key => $value) {
if($value['product_id'] == 8) {
$matching_products[] = $value['cat_id'];
}
}
which'll leave you with an array of cat ids that have a product id of 8
This should be able to retrieve all of the cat_id's from a given product_id. This function yields an object that can be iterated over to retrieve all the values it contains.
<?PHP
public function GetCatIdsByProductId($productId)
{
foreach($updateCategories=>products as $key=>$product)
{
if (isset($product=>product_id) && $product=>product_id == 8)
{
yield $product=>cat_id;
}
}
}
//Usage
$catIds = GetCatIdsByProductId(8);
var_dump($catIds);
A more generic version of this function can be constructed to retrieve a given key from a comparison on a given property value.
public function GetPropertyByPropertyComparison(array $list, $propRet, $propCompare, $compValue)
{
foreach($list as $key=>$product)
{
if (isset($product=>{$propCompare}) && $product=>{$propCompare} == $compValue)
{
yield $product=>{$propRet};
}
}
}
//usage
$cats = GetPropertyByPropertyComparison($updateCategories=>products, "cat_id", "product_id", 8);
var_dump($cats);
?>

Categories