php unique/group associative array - php

I would like to remove duplicates for the following array. I want to group by the first value and then rebuild the index.
ie
Array
(
[0] => Array
(
[title] => California
[state_id] => 1
)
[1] => Array
(
[title] => California
[state_id] => 1
)
[2] => Array
(
[title] => New Mexico
[state_id] => 2
)
[3] => Array
(
[title] => Washington
[state_id] => 3
)
[4] => Array
(
[title] => Montana
[state_id] => 4
)
[5] => Array
(
[title] => Montana
[state_id] => 4
)
)
To
Array
(
[0] => Array
(
[title] => California
[state_id] => 1
)
[2] => Array
(
[title] => New Mexico
[state_id] => 2
)
[3] => Array
(
[title] => Washington
[state_id] => 3
)
[4] => Array
(
[title] => Montana
[state_id] => 4
)
)
and rebuild key
Array
(
[0] => Array
(
[title] => California
[state_id] => 1
)
[1] => Array
(
[title] => New Mexico
[state_id] => 2
)
[2] => Array
(
[title] => Washington
[state_id] => 3
)
[3] => Array
(
[title] => Montana
[state_id] => 4
)
)

$array = array_values(array_combine(array_map(function ($i) { return $i['title']; }, $array), $array));
I.e.
extract the title key (array_map)
use the extracted titles as keys for a new array and combine it with the old one (array_combine), which de-duplicates the array (keys have to be unique)
run the result through array_values, which discards the keys
Broken down:
$keys = array_map(function ($i) { return $i['title']; }, $array);
$deduped = array_combine($keys, $array);
$result = array_values($deduped);
For PHP 5.2- you'll need to write the anonymous callback function like this:
array_map(create_function('$i', 'return $i["title"];'), $array)

Sort your array by title (usort does the trick)
create a new empty array
Cycle original array and store the value you find in the new empty array
If next array value equals last then skip it
At the end of this you have the array you want.
There is another way:
Sort your array by title
Cycle original array
If this array value equals last then unset it
Sort the array again with PHP sort function to rebuild keys

$array = array_unique($array);
Yes, it works with multi-dimentional arrays too; it just checks to equality.

Related

Sort array by date

My array has an array for each field (i.e date, name, etc.). How do I sort the array by date? Should I create another array? Can I use sort or unsort here. If yes, how? Here is my array:
Array
(
[date] => Array
(
[0] => 03/11/2019
[1] => 03/19/2019
[2] => 03/15/2019
[3] => 12/15/2018
)
[name] => Array
(
[0] => Lowa
[1] => Stephanie
[2] => Allan
[3] => Joffer
)
[number] => Array
(
[0] => 178989898
[1] => 111111111
[2] => 222222222
[3] => 333333333
)
[unit] => Array
(
[0] => HR
[1] => VPP
[2] =>
[3] => OAT
)
[department] => Array
(
[0] => Chemistry
[1] => IT
[2] => Lab
[3] => Contractor
)
)
At the end, my first element will be:
03/19/2019 Stephanie 111111111 VPP IT
I think your data can be better organized:
$newArr = Array
(
[0] => Array
(
[date] => 03/11/2019
[name] => Lowa
[number] => 178989898
[unit] => HR
[department] => Chemistry
)
[1] => Array
(
[date] => 03/19/2019
[name] => Stephanie
[number] => 111111111
[unit] => VPP
[department] => IT
)
[2] => Array
(
[date] => 03/15/2019
[name] => Allan
[number] => 222222222
[unit] =>
[department] => Lab
)
[3] => Array
(
[date] => 12/15/2018
[name] => Joffer
[number] => 333333333
[unit] => OAT
[department] => Contractor
)
);
Then, you can simply sort it by:
function cmp($a, $b) {
if ($a["date"] == $b["date"]) return 0;
return ($a["date"] < $b["date"]) ? -1 : 1;
}
usort($newArr, "cmp");
Please be warned that dates in the format "Month/Day/Year" ar not alphabetically sortable.
You definitively should use a Year/Month/Day format for your dates, or write a more specific cmp() function...
UPDATE: To answer OP's question in comment: just reverse $row and 'field' order:
for ($row = 0; $row < count($date); $row++) {
$newArr[$row]['date'] = $date[$row];
$newArr[$row]['name'] = $name[$row];
...
}
First save the keys of your array - then by using array_value convert to integer keys so you can use the ... operator.
Then you can use array_filter with null function to re-organize your array. Next step will be to get the keys back using array_map and array_combine.
Last step - sort by "data" with usort
Consider the following example:
$arr = ["date" => ["3", "7", "5"], "name" => ["aa", "bb", "cc"]]; // this can have a lot more sub-array inside
$keys = array_keys($arr); // extract the keys for later use
$res = array_map(null, ...array_values($arr)); // transposed the array
$res = array_map(function ($e) use ($keys) {return array_combine($keys, $e);}, $res); // return the keys to the transposed array
usort($res, function ($a, $b) {return strcmp($a['date'], $b['date']);} ); // sort all by "date"
Reference:
array-keys, array-filter, array-map, usort, array-values
Notice #MarcoS post comment regarding the comparing dates

How to remove particular index from array

I have an array [0,1,2,3,4] if i got ApplicationStatus = 868 at first then it return only that value other are remove from array. My actual array and i want expected array as below.
Actual Array -
Array
(
[0] => Array
(
[Name] => DENNIS VICENCIO BLANCO
[ApplicationStatus] => 826
)
[1] => Array
(
[Name] => ARPITA RANJAN DUTTA
[ApplicationStatus] => 826
)
[2] => Array
(
[Name] => MARLUNA LIM URUBIO
[ApplicationStatus] => 868
)
[3] => Array
(
[Name] => BREDJET - ALEXANDER
[ApplicationStatus] => 868
)
[4] => Array
(
[Name] => DENNIS VICENCIO BLANCO
[ApplicationStatus] => 826
)
)
Expected Array -
Array
(
[0] => Array
(
[Name] => DENNIS VICENCIO BLANCO
[ApplicationStatus] => 826
)
[1] => Array
(
[Name] => ARPITA RANJAN DUTTA
[ApplicationStatus] => 826
)
[2] => Array
(
[Name] => MARLUNA LIM URUBIO
[ApplicationStatus] => 868
)
)
So,how to remove remaining key from array.please suggest mi appropriate solution for this.
You can use array slice function:
$desired_array = array();
for($i = 0; $i < count($my_array); $i++)
{
if($my_array[$i]["ApplicationStatus"] == 868)
{
$desired_array = array_slice($my_array, 0, $i);
}
}
Not very clear, but you can delete a value from an array with unset() function.
For example:
unset($arr[3]); // removes array with key = 3
...but I would use the array_filter() and would create a function to select the right elements what I need.

Rearrange array values according to another array values in php

I have got 2 arrays(One single and one multidimensional).
Single array "A" looks like
[questionid] => Array
(
[0] => 12
[1] => 13
[2] => 55
[3] => 15
[4] => 16
)
Multidimensional array "B" looks like
Array
(
[0] => Array
(
[quid] => 12
[answer] => AAA
)
[1] => Array
(
[quid] => 13
[answer] => neighbour
)
[2] => Array
(
[quid] => 15
[answer] =>
)
[3] => Array
(
[quid] => 16
[answer] =>
)
[4] => Array
(
[quid] => 55
[answer] =>
)
)
Now I want the array B (quid) values to be rearranged depending upon the values from array A. So in array B the value of quid last element(55) is at the very end whereas in array A it is in 3rd position.
I want the array B look like this
Array
(
[0] => Array
(
[quid] => 12
[answer] => AAA
)
[1] => Array
(
[quid] => 13
[answer] => neighbour
)
[2] => Array
(
[quid] => 55
[answer] =>
)
[3] => Array
(
[quid] => 15
[answer] =>
)
[4] => Array
(
[quid] => 16
[answer] =>
)
)
The code for multidimensional array is
$ansid = array
(
array
(
"quid" => 12,
"answer" => "AAA"
),
array
(
"quid" => 13,
"answer" => "neighbour"
),
array
(
"quid" => 15,
"answer" =>""
),
array
(
"quid" => 16,
"answer" =>""
),
array
(
"quid" => 55,
"answer" =>""
)
);
Not using array_walk() as to be mor demonstrative, you could just
$newB=array()
foreach ($arrayB as $b) $newB[$b['quid']]=$b;
$newA=array()
foreach ($arrayA as $k=>$v) $newA[$k]=$newB[$v]
//$newA has the required structure
With the user sort function:
$single_array = ...; // order by the index of this array
$mult_dim_array = ...; // to be ordered by the 'quid' value of the elements
function my_comp($a, $b) {
return array_search($a['quid'], $single_array ) - array_search($b['quid'], $single_array );
}
usort($mult_dim_array, "my_comp");
This will get the index on your first array to determine which element goes first or later. The function reads $single_array as a global variable (defined outside the function).
Documentation at http://php.net/manual/en/function.usort.php

How to remove duplicate values compare two array

I have two array.
one
Array
(
[0] => Array
(
[driverId] => 3
[latitude] => 23.752182
[longitude] => 90.377730
[distance] => 0
[EstTime] => 0
)
[1] => Array
(
[driverId] => 6
[latitude] => 23.752782
[longitude] => 90.375730
[distance] => 0.2341134331552646
[EstTime] => 133
)
)
two
Array
(
[0] => Array
(
[driverId] => 3
)
[1] => Array
(
[driverId] => 61
)
)
first array store in $info and second array store in $infor
here first array item driverId is 3 and second array item driverId is 3.
so in my output i want to skip first array first item.
When looping through each array store the driverId in another array and also check that the current driverId is not in this array, if it is then we can skip it. For example:
$ids = array();
foreach($infor AS $arr2){
$ids[] = $arr2['driverId'];
}
foreach($info AS $i){
if(!in_array($i['driverId'],$ids)){
print_r($i);
}
}

PHP sort array alphabetically

I'm struggling on this one. I have an array that contains countries and regions. I want to sort both sets of information in ascending order on the key.
Here is the array I'm working with:
Array
(
[Country] => Array
(
[United Kingdom] => Array
(
[London] => Array
(
[0] => 1
[1] => 5
[2] => 23
[3] => 71
)
[Manchester] => Array
(
[0] => 800
)
)
[United States] => Array
(
[New York] => Array
(
[0] => 147
[1] => 111
)
[Washington] => Array
(
[0] => 213
)
[Florida] => Array
(
[0] => 6
)
[Texas] => Array
(
[0] => 9
)
)
[Brazil] => Array
(
[Brasília] => Array
(
[0] => 64
)
)
)
)
So the reordered array would be:
Brazil
- Brasília
United Kingdom
- London
- Manchester
United States
- Florida
- New York
- Texas
- Washington
The data structure should remain the same, but the order of the number (e.g. London: 1,5,23,71) can stay the same.
I've tried several of the sorting methods from:
http://php.net/manual/en/array.sorting.php
But they dont appear to do anything. Maybe because its a multidimensional array or maybe its not structured 100% logically... but I'm stuck with the array as it is.
You can try:
ksort_recursive($data);
print_r($data);
Function Used
function ksort_recursive(&$array) {
ksort($array);
foreach ( $array as &$a ) {
is_array($a) && ksort_recursive($a);
}
}
See Testing on Multiple PHP Versions
Step 1:
Sort the country by key.
ksort($arr['Country']);
Step 2: Loop through the countries and sort those keys.
foreach ($arr['Country'] as $country=>$data) {
ksort($arr['Country'][$country]);
}

Categories