PHP remove duplicate array values - php

Let me explain my situation,
i got myself a multidimensional array..
Down below is the print_r of my array.
Array
(
[0] => Array
(
[firstname] => Tinga
[lastname] =>
[email] => private#information.nl
[country_code] => NL
[group] => B2B
[order_count] => 321
)
[1] => Array
(
[firstname] => Tinga
[lastname] =>
[email] => private#information.nl
[country_code] => NL
[group] => B2B
[order_count] => 12
)
[2] => Array
(
[firstname] => Rijsbergen Automotive B.V.
[lastname] =>
[email] => private#information1.nl
[country_code] => NL
[group] => B2B
[order_count] => 311
)
[3] => Array
(
[firstname] => Mike Verhoef
[lastname] => Artis Garage Amsterdam
[email] => private#information2.nl
[country_code] => NL
[group] => B2B
[order_count] => 260
)
[4] => Array
(
[firstname] => Marc Kraak
[lastname] => Vakgarage TEMA
[email] => private#information3.nl
[country_code] => NL
[group] => B2B
[order_count] => 257
)
[5] => Array
(
[firstname] => J&B Auto's
[lastname] =>
[email] => private#information4.nl
[country_code] => NL
[group] => B2B
[order_count] => 249
)
)
As you can see, there is a duplicate array, only the order_count is different.
I can easily remove the duplicates using array_unique, but then it removes one of the arrays randomly(i believe).
What i want is to remove the duplicates based on email (private_information) with the least amount of order_count. (So only keep the one with the highest order_count)
Anyone who can help me out here?

Solution based on provided array is:
$filtered = [];
foreach ($array as $item) {
$email = $item['email'];
if (empty($filtered[$email]) || $filtered[$email]['order_count'] < $item['order_count']) {
$filtered[$email] = $item;
}
}

Related

Extract Data from Multidem array

I have been trying to extract the following data for each student from a large multidimensional array (Shown further down)
Data -> gender,
Data -> grade,
Data -> name -> first,
Data -> name -> last,
Data -> name -> middle,
Data -> student_number,
Data -> ID
I have tried various options through searching including Slice, Splice, and a for loop.
Every attempt has been met with failure on all or some of the data. I have never been able to get to the 3rd nested data of First, Middle, and Last name.
How can I take a large multidem array like this, and extract the data listed above in a foreach loop so I can import it into a database? I feel like it is alot simpler than I am making it. I have not included any code as I have yet to have anything that seems remotely useful.
Here is a sample array below. Thanks!
Array
(
[data] => Array
(
[0] => Array
(
[data] => Array
(
[gender] => M
[dob] => 7/17/2008
[email] =>
[grade] => 2
[schools] => Array
(
[0] =>12345
)
[school] => 12345
[created] => 2018-04-16T14:01:00.437Z
[name] => Array
(
[first] => Jacob
[last] => Smith
[middle] => Rabbitboom
)
[location] => Array
(
[zip] =>
[address] =>
[city] =>
[lat] =>
[lon] =>
[state] =>
)
[district] => 123456
[last_modified] => 2018-04-16T14:01:00.437Z
[race] =>
[hispanic_ethnicity] =>
[graduation_year] =>
[student_number] => 1234567
[credentials] => Array
(
[district_username] =>
)
[id] => 123456
)
[uri] =>
)
[1] => Array
(
[data] => Array
(
[gender] => F
[dob] => 7/17/2008
[email] =>
[grade] => 2
[schools] => Array
(
[0] =>12346
)
[school] => 12345
[created] => 2018-04-16T14:01:00.437Z
[name] => Array
(
[first] => Jason
[last] => Smith
[middle] => RobesPerrie
)
[location] => Array
(
[zip] =>
[address] =>
[city] =>
[lat] =>
[lon] =>
[state] =>
)
[district] => 123456
[last_modified] => 2018-04-16T14:01:00.437Z
[race] =>
[hispanic_ethnicity] =>
[graduation_year] =>
[student_number] => 1234568
[credentials] => Array
(
[district_username] =>
)
[id] => 123459
)
[uri] =>
)
The easiest approach might be to extract the nested data arrays and loop that:
foreach(array_column($array['data'], 'data') as $data) {
echo $data['gender'];
echo $data['name']['first'];
}
If schools is variable length then you'll need to loop that or implode(', ', $data['schools']).

array undefined offset with php

<?php
$ar = Array (
[0] => Array ( [id] => 1 [social_id] => [role_id] => 0 [name] => [first_name] => Jimmy [last_name] => rathore [gender] => male [dob] => 06-02-1992 [language] => english [location] => xyz [address] => xyz [email] => xyz#xyz.com [phone] => 9876543210 )
[1] => Array ( [id] => 3 [social_id] => [role_id] => 0 [name] => [first_name] => Dev [last_name] => Smith [gender] => [dob] => [language] => [location] => xyz [address] => xyz [email] => yyy#sds.com [phone] => 7838344344 )
[2] => Array ( [id] => 4 [social_id] => [role_id] => 0 [name] => [first_name] => Col [last_name] => Manon [gender] => male [dob] => 02-02-2017 [language] => english [location] => London [address] => ABCD [email] => londs#an.com [phone] => 7894561230)
) ;
$array = Array (
[0] => Array ( [id] => 1 [sm_id] => 1 [field_name] => first_name [value] => G2 [created_at] => 2017-02-24 11:05:03 [updated_at] => 2017-02-24 11:05:03 [deleted_at] => )
);
$arr = array();
foreach($row=0; $row<count($ar); $row++){
foreach($col=0; $col<count($array); $col++){
if($ar['0']['id'] == $array['0']['id']){
$arr['first_name'] = $ar['0']['first_name'];
$arr['last_name'] = $ar['0']['last_name'];
$arr['email'] = $ar['0']['email'];
$arr['phone'] = $ar['0']['phone'];
}
}
}
print_r($arr);die;
?>
I want map data from one array to other array based on $ar['0]['id'] with $array['0']['sm_id']
if $ar's id matched with $array's sm_id push to one array with its value how can i achieve the same. please suggest
Expected result
Array( [id] => 1 [first_name] => Jimmy [last_name] => rathore [gender] => male [dob] => 06-02-1992 [language] => english [location] => xyz [address] => xyz [email] => xyz#xyz.com [phone] => 9876543210 );
You could do it like this, given the original array is $ar, and the array with sm_id values $array:
// Create a hash of all sm_id values to be found
$ids = array_flip(array_column($array, "sm_id"));
// filter the original array to get only those with an id value in that hash
$arr = array_filter($ar, function ($row) use ($ids) {
return isset($ids[$row["id"]]);
});
print_r ($arr);

How to insert a new values pair in an associative array in PHP?

I've an associative array. I am attempting to create each sub array within a loop and insert it into a multidimensional array. Google suggested using array_merge, but after using 'print_r' on the multidimensional array with the code below, only the last sub-array is being displayed.
Array
(
[data] => Array
(
[0] => Array
(
[candidate] => Array
(
[id] => 184
[firstName] => skg
[lastName] => s
[address] => Array
(
[address1] => sakthi
[address2] =>
[city] =>
[state] =>
[zip] =>
[countryID] => 1
[countryName] => United States
[countryCode] => US
)
[hourlyRate] => 0
)
[jobOrder] => Array
(
[id] => 88
[title] => Tech Analyst
)
)
[1] => Array
(
[candidate] => Array
(
[id] => 852
[firstName] => mso cool
[lastName] =>
[address] => Array
(
[address1] =>
[address2] =>
[city] =>
[state] =>
[zip] =>
[countryID] => 1
[countryName] => United States
[countryCode] => US
)
[hourlyRate] => 0
)
[jobOrder] => Array
(
[id] => 57
[title] => Tester
)
)
And Another Array like this :
[rating] => Array
(
[0] => 7
[1] => 5
[2] =>
)
How to get merge this array value into previous array values like
Array
(
[data] => Array
(
[0] => Array
(
[candidate] => Array
(
[id] => 184
[firstName] => skg
[lastName] => s
[address] => Array
(
[address1] => sakthi
[address2] =>
[city] =>
[state] =>
[zip] =>
[countryID] => 1
[countryName] => United States
[countryCode] => US
)
[hourlyRate] => 0
[rating] => 7
)
[jobOrder] => Array
(
[id] => 88
[title] => Tech Analyst
)
)
[1] => Array
(
[candidate] => Array
(
[id] => 852
[firstName] => mso cool
[lastName] =>
[address] => Array
(
[address1] =>
[address2] =>
[city] =>
[state] =>
[zip] =>
[countryID] => 1
[countryName] => United States
[countryCode] => US
)
[hourlyRate] => 0
[rating] => 5
)
[jobOrder] => Array
(
[id] => 57
[title] => Tester
)
)
I tried lot of tricks but couldn't get the desired array format. Can any one help me in this to get the desired array? Thanks in advance.
$arr = array(); //filled with data
$rating = array(); //filled with rates
foreach ( $rating as $key =>$rate ) {
$arr['data'][ $key ]['rating'] = $rate;
}
<?php
$arr=Array(
'data'=>Array(
0=>Array('candidate'=>Array()),
1=>Array('candidate'=>Array())
)
);
$rating=Array(7,5);
foreach($rating as $key=>$val){
$arr['data'][$key]['rating']=$val;
}
print_r($arr);
Returns:
Array
(
[data] => Array
(
[0] => Array
(
[candidate] => Array
(
)
[rating] => 7
)
[1] => Array
(
[candidate] => Array
(
)
[rating] => 5
)
)
)

how to usort an array which is already sorted with another key

my first array is already sorted by name,but i want to usort it with position,
what i have tried is here,
array before usort
Array
(
[0] => Array
(
[name] => admin
[designation] => admin
[email] => admin#admin
[phone] => 999777788
[ext] => 67767
[position] => 1
[image] =>
)
[1] => Array
(
[name] => ATeam
[designation] => Manager
[email] => service#mail.com
[phone] =>
[ext] => 777
[position] => 3
[image] =>
)
[2] => Array
(
[name] => BTeam
[designation] => Manager
[email] =>g#mail.co.in
[phone] =>
[ext] =>
[position] => 4
[image] =>
)
[3] => Array
(
[name] => hi team
[designation] => new
[email] => abc
[phone] => 3333
[ext] => 333
[position] => 10
[image] =>
)
[4] => Array
(
[name] => new team
[designation] => maneger
[email] => mg#g
[phone] => 445567676
[ext] => ext
[position] => 10
[image] =>
)
)
usort function i applied to the array is:
usort($a_teams,function($a,$b){
if($a['position'] == '') return 1;
if($b['position'] == '') return -1;
return $a['position']-$b['position'];
});
the result array is:
Array
(
[0] => Array
(
[name] => admin
[designation] => admin
[email] => admin#admin
[phone] => 999777788
[ext] => 67767
[position] => 1
[image] =>
)
[1] => Array
(
[name] => ATeam
[designation] => Manager
[email] => service#mail.com
[phone] =>
[ext] => 777
[position] => 3
[image] =>
)
[2] => Array
(
[name] => BTeam
[designation] => Manager
[email] => g#mail.co.in
[phone] =>
[ext] =>
[position] => 4
[image] =>
)
[3] => Array
(
[name] => new team
[designation] => maneger
[email] => mg#g
[phone] => 445567676
[ext] => ext
[position] => 10
[image] =>
)
[4] => Array
(
[name] => hi team
[designation] => new
[email] => abc
[phone] => 3333
[ext] => 333
[position] => 10
[image] =>
)
)
but the problem is the alphabetical order of name is not getting in proper order when the positions is same
Changed the usort function for sorting by position and name:
usort($a_teams,function($a,$b){
if ($a["position"]==$b["position"]){
return strcmp($a["name"], $b["name"]);
}
return ($a["position"]<$b["position"])?-1:1;
});
Changed the usort function for sorting by position and name:
usort($a_specials,function($a,$b){
if($a['position'] == '') return 1;
if($b['position'] == '') return -1;
if($a['position'] == $b['position'])
return strnatcmp($a['title'],$b['title']);
return $a['position']-$b['position'];
});

iterate through array with foreach php

Any idea how to access creator with foreach? I receive this as a result from the linkedin groups API and want to iterate through it, after joining the first level with foreach($data as $value) - I am not sure how to iterate through the second and third array to access the values for creator
Array
(
[_total] => 4
[values] => Array
(
[0] => Array
(
[creator] => Array
(
[firstName] => Martin
[headline] => test1
[id] => DNz_ycOHn5
[lastName] => asdf
[pictureUrl] => https://media.licdn.com
)
[summary] => hi summary
[title] => hi title
)
[1] => Array
(
[creator] => Array
(
[firstName] => Martin
[headline] => test2
[id] => DNz_ycOHn5
[lastName] => asdf
[pictureUrl] => https://media.licdn.com
)
[summary] => summary
[title] => testpost
)
[2] => Array
(
[creator] => Array
(
[firstName] => Martin
[headline] => test3
[id] => DNz_ycOHn5
[lastName] => asdf
[pictureUrl] => https://media.licdn.com
)
[summary] => 12312
[title] => linkedinDEV
)
[3] => Array
(
[creator] => Array
(
[firstName] => Martin
[headline] => test4
[id] => DNz_ycOHn5
[lastName] => asdf
[pictureUrl] => https://media.licdn.com
)
[summary] => test123
[title] => Discussion Title
)
)
)
best
M
Since 5.5, you can use in this case array_column:
$creators = array_column($data['values'],'creator');
This will create an array of creators:
$creators = array();
foreach($data['values'] as $value) {
$creators[] = $value['creator'];
}
// An array containing the creator information
var_dump($creators);

Categories