array unique for multi dimensional array in php [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.
First of all this is not a duplicate question as i have tried most of the stack answer.
I have about 138886 records in my array.
records are like
[1] => Array
(
[country] => US
[state] => Albama
[city] => Brest
[postcode] => 225001-225003
[shipping_info] => Delivery Available
[is_zip_range] => 1
[zip_from] => 225001
[zip_to] => 225003
)
[2] => Array
(
[country] => BY
[state] => Brest
[city] => Brest
[postcode] => 225001-225003
[shipping_info] => Delivery Available
[is_zip_range] => 1
[zip_from] => 225001
[zip_to] => 225003
)
I want to unique all record from postcode value i have tried some method are
Method 1
$temp = array_unique(array_column($data, 'postcode'));
$filteredData = array_intersect_key($data, $temp);
but it is still giving duplicate value.
Method 2
$filteredData = array_map("unserialize", array_unique(array_map("serialize", $data)));
this is won't work
Method 3
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($array,'postcode');
It is working but too slow taking about 2/3 mins.
let me know any other method i can use for unique array.
help will be apprecitaed

Why are you making it so hard,
$in = array (
1 =>
array (
'country' => 'US',
'state' => 'Albama',
'city' => 'Brest',
'postcode' => '225001-225003',
'shipping_info' => 'DeliveryAvailable',
'is_zip_range' => 1,
'zip_from' => 225001,
'zip_to' => 225003
),
2 =>
array (
'country' => 'BY',
'state' => 'Brest',
'city' => 'Brest',
'postcode' => '225001-225003',
'shipping_info' => 'DeliveryAvailable',
'is_zip_range' => 1,
'zip_from' => 225001,
'zip_to' => 225003
)
);
$out = [];
foreach($in as $i) if(!isset($out[$i['postcode']])) $out[$i['postcode']] = $i;
Sandbox
You can do the same thing with in_array, but the isset is faster.
In fact you dont even need to do the isset
foreach($in as $i) $out[$i['postcode']] = $i;
Array keys are always unique, but this will retain the last duplicate where as the previous code keeps the first one.
And if the keys bug you latter just do $out = array_values($out) to reset them.

Related

php merge arrays and change its grouping [duplicate]

I have a multidimensional array and am trying to group them according to the value in a specific column.
I'm trying to group them by level, but I won't actually know the level beforehand. So, it's not like I can put it in a for loop and say while $i < 7, because I won't know that 7 is the maximum value for the level key, and frankly, I'm not sure that's how I would need to do it even if I did.
[
['cust' => 'XT8900', 'type' => 'standard', 'level' => 1],
['cust' => 'XT8944', 'type' => 'standard', 'level' => 1],
['cust' => 'XT8922', 'type' => 'premier', 'level' => 3],
['cust' => 'XT8816', 'type' => 'permier', 'level' => 3],
['cust' => 'XT7434', 'type' => 'standard', 'level' => 7],
]
Desired result:
Array (
[1] => Array (
[0] => Array (
[cust] => XT8900
[type] => standard
)
[1] => Array (
[cust] => XT8944
[type] => standard
)
)
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
)
Best way, if you have control over building the initial array, is just set things up like that at the start as you add entries.
If not then build a temporary array to sort:
foreach ($input_arr as $key => &$entry) {
$level_arr[$entry['level']][$key] = $entry;
}
Leaves you with the form you wanted and everything referenced together.
Build the array like that in the first place though if at all possible.
You need to group them by level first
Use foreach to loop into array check if the level is the same with the previous item then group it with that array
$templevel=0;
$newkey=0;
$grouparr[$templevel]="";
foreach ($items as $key => $val) {
if ($templevel==$val['level']){
$grouparr[$templevel][$newkey]=$val;
} else {
$grouparr[$val['level']][$newkey]=$val;
}
$newkey++;
}
print($grouparr);
The output of print($grouparr); will display like the format you hoped for
You can also try to
print($grouparr[7]);
Will display
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
Or
print($grouparr[3]);
Will display
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)
Here is the solution I landed on for an identical problem, wrapped as a function:
function arraySort($input,$sortkey){
foreach ($input as $key=>$val) $output[$val[$sortkey]][]=$val;
return $output;
}
To sort $myarray by the key named "level" just do this:
$myArray = arraySort($myArray,'level');
Or if you didn't want it as a function, just for a one time use, this would create $myNewArray from $myArray grouped by the key 'level'
foreach ($myArray as $key=>$val) $myNewArray[$val['level']][]=$val;
function group_assoc($array, $key) {
$return = array();
foreach($array as $v) {
$return[$v[$key]][] = $v;
}
return $return;
}
//Group the requests by their account_id
$account_requests = group_assoc($requests, 'account_id');
$result = array();
foreach ($yourArrayList as $data) {
$id = $data['level'];
if (isset($result[$id])) {
$result[$id][] = $data;
} else {
$result[$id] = array($data);
}
}
Best ans.
$levels = array_unique(array_column($records, 'level'));
$data = array();
foreach($records as $key => $value){
$data[$levels[array_search($value['level'],$levels )]][] = $value ;
}
print_r($data);
To generate the question's exact desured output from the sample input, pull/pop the last value from each row, use that value as the first level grouping key. Then use the original first level index as the second level key. Then push the two remaining elements into the group's subset.
Code: (Demo)
$result = [];
foreach ($array as $key => $row) {
$result[array_pop($row)][$key] = $row;
}
var_export($result);
For functional style syntax, use array_reduce(). (Demo)
var_export(
array_reduce(
array_keys($array),
function($result, $key) use ($array) {
$result[array_pop($array[$key])][$key] = $array[$key];
return $result;
}
)
);
function _group_by($array,$key,$keyName)
{
$return = array();
foreach($array as $val) {
$return[$keyName.$val[$key]][] = $val;
}
return $return;
} //end of function

counting occurence on multiple PHP array [duplicate]

This question already has answers here:
Count specific values in multidimensional array
(4 answers)
Closed 9 years ago.
I'm looking for a way to count occurence on an array of array.
This is my array :
Array
(
[0] => Array
(
[id] => 671
[title] => BIEND
[img] =>
[ville] => marseille
)
[1] => Array
(
[id] => 670
[title] => BIENC
[img] =>
[ville] => avignon
)
[2] => Array
(
[id] => 669
[title] => BIENB
[img] =>
[ville] => avignon
)
)
And what I would like to have :
Array
(
[avignon] => 2
[marseille] => 1
)
I tried with array_count_values, but it dont seems to be the good way.
Any idea?
You could just go through it manually:
$result = array();
foreach($input as $item)
{
$result[$item['ville']]++;
}
or, slightly nicer perhaps,
$result = array();
foreach($input as $item)
{
$city = $item['ville'];
if(!array_key_exists($city, $result)) {
$result[$city] = 1;
} else {
$result[$city]++;
}
}
Alternatively, you could do some array_map magic to first get an array with all the cities, and then use array_count_values as you planned:
$cities = array_count_values( array_map( function($a) { return $a['ville']; } ) );
Note, I haven't tested this last solution, I personally think the first one expresses the intention better. If you would like to use this one because it is shorter (i.e. less readable) I'll leave it to you to debug and comment it
You can use array_reduce():
$data = Array
(
0 => Array
(
'id' => 671,
'title' => 'BIEND',
'img' => '',
'ville' => 'marseille'
)
,
1 => Array
(
'id' => 670,
'title' => 'BIENC',
'img' => '',
'ville' => 'avignon'
)
,
2 => Array
(
'id' => 669,
'title' => 'BIENB',
'img' => '',
'ville' => 'avignon'
)
);
$result = array_reduce($data, function(&$cur, $x)
{
$cur[$x['ville']] = isset($cur[$x['ville']])?$cur[$x['ville']]+1:1;
return $cur;
}, []);
$my_array = array(...);
$result = array();
foreach ($my_array as $arr) {
$key = $arr['ville'];
if (! array_key_exists($key, $result){
$result[$key] = 1;
continue;
}
$result[$key] += 1;
}
I would write something like this. Array and subArray should be renamed according to their content.
$villes = array();
foreach($yourArray as $subArray) {
if(!in_array($subArray['ville'], $villes)) {
$villes[$subArray['ville']] = 1;
} else {
$villes[$subArray['ville']]++;
}
}
var_dump($villes);

using array merge into a foreach loop

I need to merge a new array of alternative information into the loop if they have the alternative information in their profile.
Here's my loop:
foreach ($doctor->getVars() as $k => $v)
{
$data['doctor_'. $k] = $v;
}
foreach ($patient->get_data() as $k=>$v)
{
if (is_string($v) || is_numeric($v))
$data["patient_" . $k] = strtoupper($v);
}
Here's the $data var_dump:
Array
(
[employee] => person
[date] => 05/08/2013
[datetime] => 05/08/2013 9:41:15 AM
[department] => stuff
[employee_ext] => 7457
[employee_email] =>
[barcode] => *NZS01*
[doctor_df_code] => 09HQ
[doctor_npi] => 1111111111
[doctor_dea] => B4574
[doctor_upin] =>
[doctor_license] =>
[doctor_phone] => (111)111-1111
[doctor_fax] => (000)000-0000
[doctor_fname] => UNDEFINED
[doctor_lname] => UNDEFINED
[doctor_title] =>
[doctor_intake_rx_caller_id] =>
[doctor_costco_rx_caller_id] =>
[doctor_reorder_rx_caller_id] =>
[doctor_address1] => 24 CABELL st
[doctor_address2] => SUITE 10
[doctor_city] => places
[doctor_state] => CA
[doctor_zip] => 91111
[doctor_active_events] =>
[doctor_dont_call] => 0
[doctor_dont_fax] => 1
)
I need to merge the below array into the above array.
Here's the print var for the function addr($dfcode):
Array
(
[0] => Array
(
[CODE_] => 09HQ
[doctor_address1] => alternate addy
[doctor_address2] => 45854
[doctor_city] => different city
[doctor_state] => CA
[doctor_zip] => 963545
[doctor_phone] => (619)111-2548
[doctor_fax] => (157)123-4569
)
)
I'm new to array merge and I'm assuming right after the $data['doctor_'. $k] = $v i could list out the new function and the fields i want to merge in particular?
syntax is what i'm not sure on:
$data['doctor_'. $k] . array_merge(addr($dfcode))['doctor_address1'] = $v;
Any help would be greatly appreciated, thank you.
The general formula for merging two arrays is as follows (merging $array_m into $array_o):
foreach($array_m as $key=>$value){
$array_o[$key] = $value;
}
$array_o would now contain all of the elements of $array_m
EDIT: I just noticed in your post that you seem to want to use the array_merge function. You could also do the following:
$array_o = array_merge($array_o, array_m);

php split Array via [name] into groups to save in MySQL

output via print_r in php from jquery.serilizeArray()
Array (
[pnr_item_2] => 2
[pkt_item_2] => Hosting L
[desc_item_2] => Domain + Hosting
[qty_item_2] => 9
[price_item_2] => 12.4
[pnr_item_1] => 1
[pkt_item_1] => HostingXXL
[desc_item_1] => 20GB, 1x.de
[qty_item_1] => 2
[price_item_1] => 15.5
[pnr_item_3] => 3
[pkt_item_3] => Domain
[desc_item_3] => Standarddomain
[qty_item_3] => 6
[price_item_3] => 5
[pnr_item_4] => 3
[pkt_item_4] => Domain
[desc_item_4] => Standarddomain
[qty_item_4] => 7
[price_item_4] => 5
[action] => save
[mysql] => update
[total] => 351.1
)
Does exist a possibility to split an Array in groups by using the _item_##-number?
I want to save items to my first MySQL table, action is the executet function, which I get via $_POST[action] and [total] have to be saved in a extra (2nd) MySQL-table.
Based on my guess at the question's meaning ;)
//$yourArr = array(all,your,input);
$action = $yourArr['action'];
$mysql = $yourArr['mysql'];
$total = $yourArr['total'];
unset( $yourArr['action'] , $yourArr['mysql'] , $yourArr['total'] );
foreach ($yourArr as $k => $v) {
list($type,$num) = explode('_item_',$k);
$items[$num][$type] = $v;
}
Than you have, for example:
$items = array(
[2]['pnr'] => 2,
[2]['pkt'] => 'Hosting L',
[2][['desc_item'] => 'Domain + Hosting'
...
);
disclaimer: I didn't actually test this
You can loop over the array:
$items = array();
foreach($array as $key=>$value) {
if(stripos($key, '_item_' !== false)) {
$items[$key] = $value;
unset($array[$key]);
}
}
Then $items contain all elements that have _item_ in the key and $array the rest.
But easier would be to save total first and remove action, mysql and total from the array. So just reversing both operations.

Group 2d array data using column value to create a 3d array

I have a multidimensional array and am trying to group them according to the value in a specific column.
I'm trying to group them by level, but I won't actually know the level beforehand. So, it's not like I can put it in a for loop and say while $i < 7, because I won't know that 7 is the maximum value for the level key, and frankly, I'm not sure that's how I would need to do it even if I did.
[
['cust' => 'XT8900', 'type' => 'standard', 'level' => 1],
['cust' => 'XT8944', 'type' => 'standard', 'level' => 1],
['cust' => 'XT8922', 'type' => 'premier', 'level' => 3],
['cust' => 'XT8816', 'type' => 'permier', 'level' => 3],
['cust' => 'XT7434', 'type' => 'standard', 'level' => 7],
]
Desired result:
Array (
[1] => Array (
[0] => Array (
[cust] => XT8900
[type] => standard
)
[1] => Array (
[cust] => XT8944
[type] => standard
)
)
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
)
Best way, if you have control over building the initial array, is just set things up like that at the start as you add entries.
If not then build a temporary array to sort:
foreach ($input_arr as $key => &$entry) {
$level_arr[$entry['level']][$key] = $entry;
}
Leaves you with the form you wanted and everything referenced together.
Build the array like that in the first place though if at all possible.
You need to group them by level first
Use foreach to loop into array check if the level is the same with the previous item then group it with that array
$templevel=0;
$newkey=0;
$grouparr[$templevel]="";
foreach ($items as $key => $val) {
if ($templevel==$val['level']){
$grouparr[$templevel][$newkey]=$val;
} else {
$grouparr[$val['level']][$newkey]=$val;
}
$newkey++;
}
print($grouparr);
The output of print($grouparr); will display like the format you hoped for
You can also try to
print($grouparr[7]);
Will display
[7] => Array (
[4] => Array (
[cust] => XT7434
[type] => standard
)
)
Or
print($grouparr[3]);
Will display
[3] => Array (
[2] => Array (
[cust] => XT8922
[type] => premier
)
[3] => Array (
[cust] => XT8816
[type] => permier
)
)
Here is the solution I landed on for an identical problem, wrapped as a function:
function arraySort($input,$sortkey){
foreach ($input as $key=>$val) $output[$val[$sortkey]][]=$val;
return $output;
}
To sort $myarray by the key named "level" just do this:
$myArray = arraySort($myArray,'level');
Or if you didn't want it as a function, just for a one time use, this would create $myNewArray from $myArray grouped by the key 'level'
foreach ($myArray as $key=>$val) $myNewArray[$val['level']][]=$val;
function group_assoc($array, $key) {
$return = array();
foreach($array as $v) {
$return[$v[$key]][] = $v;
}
return $return;
}
//Group the requests by their account_id
$account_requests = group_assoc($requests, 'account_id');
$result = array();
foreach ($yourArrayList as $data) {
$id = $data['level'];
if (isset($result[$id])) {
$result[$id][] = $data;
} else {
$result[$id] = array($data);
}
}
Best ans.
$levels = array_unique(array_column($records, 'level'));
$data = array();
foreach($records as $key => $value){
$data[$levels[array_search($value['level'],$levels )]][] = $value ;
}
print_r($data);
To generate the question's exact desured output from the sample input, pull/pop the last value from each row, use that value as the first level grouping key. Then use the original first level index as the second level key. Then push the two remaining elements into the group's subset.
Code: (Demo)
$result = [];
foreach ($array as $key => $row) {
$result[array_pop($row)][$key] = $row;
}
var_export($result);
For functional style syntax, use array_reduce(). (Demo)
var_export(
array_reduce(
array_keys($array),
function($result, $key) use ($array) {
$result[array_pop($array[$key])][$key] = $array[$key];
return $result;
}
)
);
function _group_by($array,$key,$keyName)
{
$return = array();
foreach($array as $val) {
$return[$keyName.$val[$key]][] = $val;
}
return $return;
} //end of function

Categories