How to remove subarrays based on duplicate element in subarray? [duplicate] - php

This question already has answers here:
Filter/Remove rows where column value is found more than once in a multidimensional array
(4 answers)
Closed 9 months ago.
How can I check and remove duplicates from the array based on ProductReference?
This is my array:
Array
(
[0] => Array
(
[Order] => 1
[Name] => pro book 40X80
[ProductReference] => FM7291
[Description] => pro book
[Product_type] => photobook
[Pages] => 20
[AdicRange] => 2
[Width] => 40
[Height] => 40
[AvailableOption] => 0
[PicPreviews] => Array
(
[PicPreview] => Array
(
[UrlOriginal] => http://dnmyog93u35ow.cloudfront.net/assets/software/xl_1491302876209.png
[UrlThumb] => http://dnmyog93u35ow.cloudfront.net/assets/software/xs_1491302876209.png
)
)
[SubCategories] => Array
(
)
)
[1] => Array
(
[Order] => 1
[Name] => pro book 40X80
[ProductReference] => FM7291
[Description] => pro book
[Product_type] => photobook
[Pages] => 20
[AdicRange] => 2
[Width] => 40
[Height] => 40
[AvailableOption] => 0
[PicPreviews] => Array
(
[PicPreview] => Array
(
[UrlOriginal] => http://dnmyog93u35ow.cloudfront.net/assets/software/xl_1491302876209.png
[UrlThumb] => http://dnmyog93u35ow.cloudfront.net/assets/software/xs_1491302876209.png
)
)
[SubCategories] => Array
(
)
)
[2] => Array
(
[Order] => 2
[Name] => 21X29 booklet Ver
[ProductReference] => DF0754(A4)
[Description] => 29X21 booklet Ver
[Product_type] => photobook
[Pages] => 24
[AdicRange] => 4
[Width] => 20.3
[Height] => 29.9
[AvailableOption] => 0
[PicPreviews] => Array
(
[PicPreview] => Array
(
[UrlOriginal] => http://dnmyog93u35ow.cloudfront.net/assets/software/xl_1495636546424.jpg
[UrlThumb] => http://dnmyog93u35ow.cloudfront.net/assets/software/xs_1495636546424.jpg
)
)
[SubCategories] => Array
(
)
)
)

This one-liner will overwrite earlier subarrays when a new duplicate subarray is found: (Demo)
$array=array_values(array_column($array,null,"ProductReference"));
This two-liner will retain earlier subarrays and discard later ones: (Demo)
$rekeyed=array_column(array_reverse($array),null,"ProductReference");
sort($rekeyed);
apokryfos has identified the shortest/sweetest method to retain earlier subarrays and remove later ones: (Demo)
$array=array_unique($array,SORT_REGULAR);
// if the keys are important wrap array_unique() with array_values()

Make the unique value your key:
$newArray = array();
foreach($oldArray as $product){
$newArray[$product['ProductReference']] = $product;
}

This may solve your problem or guide you.You can remove duplicate based on any key.Yes if you can make in database query go for that, that will be better. Directly copied from php manual
<?php
$details = array(
0 => array("id"=>"1", "name"=>"Mike", "num"=>"9876543210"),
1 => array("id"=>"2", "name"=>"Carissa", "num"=>"08548596258"),
2 => array("id"=>"1", "name"=>"Mathew", "num"=>"784581254"),
);
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$details = unique_multidim_array($details,'id');
var_dump($details);
output
$details = array(
0 => array("id"=>"1","name"=>"Mike","num"=>"9876543210"),
1 => array("id"=>"2","name"=>"Carissa","num"=>"08548596258"),
);

Related

Split the array in to sub arrays based on array key value [duplicate]

This question already has answers here:
How to group subarrays by a column value?
(20 answers)
Closed 1 year ago.
I am facing one issue while splitting array by key value. My array looks like below :-
Array
(
[0] => Array
(
[product_id] => 6
[brand_id] => 2
)
[1] => Array
(
[product_id] => 1
[brand_id] => 1
)
[2] => Array
(
[product_id] => 5
[brand_id] => 1
)
)
Now i want to filter split the array based on brand_id. My expected output is like below:-
Array(
[0] => Array(
[0] => Array
(
[product_id] => 6
[brand_id] => 2
)
)
[1] => Array(
[0] => Array
(
[product_id] => 1
[brand_id] => 1
)
[1] => Array
(
[product_id] => 5
[brand_id] => 1
)
)
)
My Input array is stored in $proArray variable
My attempt below:-
$brands = array();
foreach ($proArr as $key => $pro) {
$brands[] = $pro['brand_id'];
}
$brands = array_unique($brands);
$ckey = 0;
foreach($brands as $brand){
}
One way to do it with simple foreach() loop to push values based on your brand_id like below-
$key = 'brand_id';
$return = array();
foreach($array as $v) {
$return[$v[$key]][] = $v;
}
print_r($return);
WORKING DEMO: https://3v4l.org/bHuWV
Code:
$arr = array(
array(
'product_id' => 6,
'brand_id' => 2
),
array(
'product_id' => 1,
'brand_id' => 1
),
array(
'product_id' => 5,
'brand_id' => 1
)
);
$res = [];
foreach ($arr as $key => $value)
$res[$value['brand_id']][] = $value;
$res = [...$res];
print_r($res);
Output:
Array
(
[0] => Array
(
[0] => Array
(
[product_id] => 6
[brand_id] => 2
)
)
[1] => Array
(
[0] => Array
(
[product_id] => 1
[brand_id] => 1
)
[1] => Array
(
[product_id] => 5
[brand_id] => 1
)
)
)

PHP Compare Arrays and clear all key if one in a array is empty

I'm looking for a solution to compare multiplay arrays with each of them i want to unset in all arrays if one key is empty. So as a example if [keywords] is empty i want to unset in all arrays [keywords]. Here are my arrays that i print_r.
Array
(
[0] => Array
(
[id] => 1
[pid] => 3
[sorting] => 128
[tstamp] => 1503039725
[title] => test
[alias] => test-3
[author] => 1
[inColumn] => main
[keywords] =>
[showTeaser] =>
[teaserCssID] =>
[teaser] =>
[printable] =>
[customTpl] =>
[protected] =>
[groups] =>
[guests] =>
[cssID] =>
[space] =>
[published] => 1
[start] =>
[stop] =>
)
[1] => Array
(
[id] => 2
[pid] => 3
[sorting] => 256
[tstamp] => 1503045056
[title] => test 2
[alias] => test-2
[author] => 1
[inColumn] => main
[keywords] =>
[showTeaser] =>
[teaserCssID] => a:2:{i:0;s:0:"";i:1;s:0:"";}
[teaser] =>
[printable] =>
[customTpl] =>
[protected] =>
[groups] =>
[guests] =>
[cssID] => a:2:{i:0;s:0:"";i:1;s:0:"";}
[space] => a:2:{i:0;s:0:"";i:1;s:0:"";}
[published] => 1
[start] =>
[stop] =>
)
)
What i have tried so far is
print_r($arrResult);
foreach($arrResult as $Result)
{
foreach ($Result as $arrKey => $arrField)
{
if(!empty($arrField))
{
$arrAllowedField[$arrKey] = $arrKey;
}
}
}
That build a array that contains the key which has values. But the problem is, that it also add empty fields of a other array.
Thanks
// remove empty entries in each array
$ar = array_map('array_filter', $ar);
// find keys having not empty value at least in one array
$temp = array_intersect_key(...$ar);
// save only keys from temp array
foreach($ar as &$item) {
$item = array_intersect_key($item, $temp);
}
demo
It removes the all the empty values from the array
$arrResult = array_map('array_filter', $arrResult);
$arrResult = array_filter( $arrResult );
echo "<pre>";
print_r($arrResult);
Output
Array
(
[0] => Array
(
[id] => 1
[pid] => 3
[sorting] => 128
[tstamp] => 1503039725
[title] => test
[alias] => test-3
[author] => 1
[inColumn] => main
[published] => 1
)
)

Combine Arrays into One Multidimensional Array using PHP

I am trying to combine arrays into one single multidimensional array. There could be more than 5 arrays that needs to be combined so I need a code that will automatically combine all arrays no matter how many they are. I tried array_merge but it requires manual defining of arrays in comma formatted parameters.
The code to convert is:
Array
(
[id] => 1
[name] => Item 1
[slug] => item-slug-1
[parent] => 0
)
Array
(
[id] => 2
[name] => Item 2
[slug] => item-slug-2
[parent] => 1
)
Array
(
[id] => 3
[name] => Item 3
[slug] => item-slug-3
[parent] => 2
)
Array
(
[id] => 4
[name] => Item 4
[slug] => item-slug-4
[parent] => 3
)
Array
(
[id] => 5
[name] => Item 5
[slug] => item-slug-5
[parent] => 3
)
And this is how I would like it to look:
Array
(
[0] => Array
{
[id] => 1
[name] => Item 1
[slug] => item-slug-1
[parent] => 0
}
[1] => Array
{
[id] => 2
[name] => Item 2
[slug] => item-slug-2
[parent] => 1
}
[2] => Array
{
[id] => 3
[name] => Item 3
[slug] => item-slug-3
[parent] => 2
}
[3] => Array
{
[id] => 4
[name] => Item 4
[slug] => item-slug-4
[parent] => 3
}
[4] => Array
{
[id] => 5
[name] => Item 5
[slug] => item-slug-5
[parent] => 3
}
)
Here is how the arrays are generated:
I receive a response JSON from the server that looks like this:
[{"slug":"item-slug-1","name":"Item 1","id":1},{"slug":"item-slug-2","name":"Item 2","id":2},{"slug":"item-slug-3","name":"Item 3","id":3,"children":[{"slug":"item-slug-4","name":"Item 4","id":4},{slug":"item-slug-5","name":"Item 5","id":5}]}]
I decode the JSON then convert it to an array like this:
$categories_obj = json_decode( $_POST['order'] );
$categories_arr = json_decode(json_encode( $categories_obj ), true);
I created a function that walks through each item so it would be easier to insert into my database:
function walk_and_update($data, $parent = 0, $count = 0) {
if( is_array($data) ) {
$combine = array();
/* The arrays are generated here */
foreach( $data as $key => $row ) {
$formatted = array(
'id' => $row['id'],
'name' => $row['name'],
'slug' => $row['slug'],
'parent' => $parent
);
print_r( $formatted );
/* My SQL update is here */
if( isset( $row['children'] ) ) {
walk_and_update( $row['children'], $row['id'], $count );
}
}
}
}
Then I use the function like this:
walk_and_update( $categories_arr );
Like this:
$arr1 = Array(
'id' => 1,
'name' => 'Item 1',
'slug' => 'item-slug-1',
'parent' => 0);
$arr2 = Array(
'id' => 2,
'name' => 'Item 2',
'slug' => 'item-slug-2',
'parent' => 1);
$arr3 = Array(
'id' => 3,
'name' => 'Item 3',
'slug' => 'item-slug-3',
'parent' => 2);
$new_arr = array();
for($i=1;$i<=3;$i++) {
$var_name = 'arr'.$i;
array_push($new_arr,$$var_name);
}
echo "<pre>";print_r($new_arr);
Output:
Array
(
[0] => Array
(
[id] => 1
[name] => Item 1
[slug] => item-slug-1
[parent] => 0
)
[1] => Array
(
[id] => 2
[name] => Item 2
[slug] => item-slug-2
[parent] => 1
)
[2] => Array
(
[id] => 3
[name] => Item 3
[slug] => item-slug-3
[parent] => 2
)
)
you could make function to handle the array, then return expected array to multidimensional array.
can i know first, that the array you want to merging , did they produce one by one or just one time that can produce many array ?
//you could do this if your array produces one time only
$counter = 0;
$new_array=array();
foreach (your array as $key => $val)
{
$new_array[$counter]['id']= $val['id'];
$new_array[$counter]['name']= $val['name'];
$new_array[$counter]['slug']= $val['slug'];
$new_array[$counter]['parent'] = $val['parent'];
$counter++;
}
//if your array produces more than one time
function main ()
{
$data['counter']=0;
$data['newarray']=array();
$data = $this->mergin_array(your array,$data['counter'])
}
function merging_array(your array,$counter)
{
$data = array();
$counter_new = $counter;
foreach(your array as $key => $val)
{
$data['newarray'][$counter]['id'] = $val['id'];
$data['newarray'][$counter]['name'] = $val['name'];
$data['newarray'][$counter]['slug'] = $val['slug'];
$data['newarray'][$counter]['parent'] = $val['parent'];
$counter_new++;
}
$data['counter'] = $counter_new;
return $data;
}
so no matter how many you use , when you access the $data['newarray'] in your main function it will get you the combined for many array

How to manipulate php arrays [duplicate]

This question already has answers here:
Group rows in an associative array of associative arrays by column value and preserve the original first level keys
(7 answers)
Closed 7 years ago.
How to manipulate php arrays. I have a $data variable below.
$data = Array
(
[0] => Array
(
[id] => 1
[capacity] => 900
[category] => users
)
[1] => Array
(
[id] => 2
[capacity] => 300
[category] => users
)
[2] => Array
(
[id] => 3
[capacity] => 900
[category] => students
)
[3] => Array
(
[id] => 4
[capacity] => 300
[category] => students
)
)
Now I want to group the data with same category like below. . I am not really familiar in php. Can somebody out there help me how to achieve this. What function should I used. Thanks
Array
(
[users] => Array
(
[0] => Array
(
[id] => 1
[capacity] => 900
[category] => users
)
[1] => Array
(
[id] => 2
[capacity] => 300
[category] => users
)
),
[students] => Array
(
[0] => Array
(
[id] => 1
[capacity] => 900
[category] => students
)
[1] => Array
(
[id] => 2
[capacity] => 300
[category] => students
)
)
)
Just iterate over the array and add it depending on the content of the category field to a new array:
$new = array();
foreach ($data as $val) {
$new[$val['category']][] = $val;
}
This does what you requested
<?php
$data = array(
0 => array (
"id" => 1,
"capacity" => 900,
"category" => "users"
),
1 => array (
"id" => 2,
"capacity" => 300,
"category" => "users"
),
2 => array (
"id" => 3,
"capacity" => 900,
"category" => "students"
),
3 => array (
"id" => 4,
"capacity" => 300,
"category" => "students"
)
);
$groups = array();
foreach ($data as $i) {
if ($i['category'] === "students") {
$groups['students'][] = $i;
}
else if ($i['category'] === "users") {
$groups['users'][] = $i;
}
}
echo "<pre>", print_r($groups), "</pre>";
Here is a working demo - http://codepad.viper-7.com/G4Br28

PHP Grouping Array by Index [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 10 months ago.
I have a multidimensional array:
Array
(
[type] => Array
(
[0] => text
[1] => portfolio
[2] => slide
[3] => text
)
[grid] => Array
(
[0] => 3
[1] => 5
[2] => 3
[3] => 4
)
[title] => Array
(
[0] => title1
[3] => title2
)
[content] => Array
(
[0] => content1
[3] => content2
)
[item] => Array
(
[1] => 6
[2] => 7
)
[pagination] => Array
(
[1] => 8
)
[order] => Array
(
[1] => desc
[2] => asc
)
)
And want to group it by [type] key given in the array:
Array (
[0] => Array (
[type] => text
[grid] => 3
[title] => title1
[content] => content1
)
[1] => Array (
[type] => portfolio
[grid] => 5
[item] => 6
[pagination] => 1
[order] => desc
)
[2] => Array (
[type] => slide
[grid] => 3
[item] => 7
[order] => asc
)
[3] => Array (
[type] => text
[grid] => 4
[title] => title2
[content] => content2
)
Is there a way or PHP function to do array grouping like that?
This snippet achieves that:
$result = array();
foreach ($array as $key => $data) {
foreach ($data as $offset => $value) {
if (isset($result[$offset])) {
$result[$offset][$key] = $value;
} else {
$result[$offset] = array($key => $value);
}
}
}
Working DEMO
array_map() with null for the callback will do exactly what you want. However it will have number for the index instead of names.
If you write your own callback then you can return an array with the names you need.
Since apparently people want the actual code:
array_map(null, $type_array, $grid_array, $title_array, $content_array, $item_array);
It really is as simple as that. Most of the other answers are so large and unnecessary.
Note: This assumes a fixed number of arrays - if it's not fixed then this won't work, and then go with Florent's answer.
You can do it with this function:
$type_array = array('text', 'portfolio', 'slide', 'text');
$grid_array = array(3, 5, 3, 4);
$title_array = array(0 => 'title1', 3 => 'title2');
$content_array = array(0 => 'content1', 3 => 'content2');
$item_array = array(1 => 6, 2 => 7);
function group_arrays($type_array, $grid_array, $title_array, $content_array, $item_array) {
$temp_array = array();
for($i = 0; $i < count($type_array); $i++) {
$temp_array[$i] = array( 'type' => #$type_array[$i],
'grid' => #$grid_array[$i],
'title' => #$title_array[$i],
'content' => #$content_array[$i],
'item' => #$item_array[$i]);
}
return $temp_array;
}
print_r(group_arrays($type_array, $grid_array, $title_array, $content_array, $item_array));
Hope this helps!

Categories