Sort 2D Array in PHP - php

I have an array that looks like this:
Array
(
[90] => Array
(
[1056] => 44.91
[1055] => 53.56
[1054] => 108.88
[1053] => 23.28
),
[63] => Array
(
[1056] => 44.44
[1055] => 53.16
[1054] => 108.05
),
[21] => Array
(
[1056] => 42.83
[1055] => 51.36
[1054] => 108.53
)
);
Both keys ([x] and [y]) refer to IDs in my database, so those need to stay intact. The order of the [x] does not matter, but I need to sort each array by the value of [y].
Edit:
I have tried this loop, but it does not seem to work:
foreach($distance as $key=>$value) {
asort($value,SORT_NUMERIC);
}

Use ksort (or uksort) to sort the arrays by their keys.
UPDATE: Use asort (or uasort) to sort by values, preserving keys.
UPDATE 2: Try this
foreach($distance as &$value) {
asort($value,SORT_NUMERIC);
}

Like this?
array_walk($array, 'asort');

Use asort() for sorting by values. It maintains the index associations.
For the loop, you need to pass $value by reference, so you need to use &$value.

array_multisort($arrindex1, SORT_DESC, $arrindex2, SORT_DESC, $array);

Related

How to extract the keys of an Array and push them to a String array?

Everyone else usually asking how to convert string array with commas to an array of key value pairs.
But my question is opposite. I want to extract the keys of the array and place them in a separate array using PHP
I have an array of this form:
Array
(
[Lights] => 4
[Tool Kit] => 4
[Steering Wheel] => 4
[Side Mirrors] => 3.5
)
and I want output to be in this form:
{"Lights", "Tool Kit", "Steering Wheel", "Side Mirrors" }
Using array_keys :
array_keys — Return all the keys or a subset of the keys of an array
So you can just extract each keys simply by using this method
$keys = array_keys($array);
Otherwise, you can loop through each values and only get the keys :
$keyArray=array_keys($array);
$keyArray=[];
foreach($array as $key => $value){
$keyArray[]=$key;
}
Use array_keys. It will return array keys as array values
$array=array('Lights' => 4,
'Tool Kit' => 4,
'Steering Wheel' => 4,
'Side Mirrors' => 3.5);
$key_array=array_keys($array);
print_r($key_array);
It will result
Array ( [0] => Lights [1] => Tool Kit [2] => Steering Wheel [3] => Side Mirrors )
Looks like you are expecting JSON output. You can just use json_encode function in a pair with array_keys.
$result = json_encode(array_keys($array));
However, your result will be ["Lights","Tool Kit","Steering Wheel","Side Mirrors"]

Get values of array using as key values of another array

I have an array with some values (numeric values):
$arr1 = [1, 3, 8, 12, 23]
and I have another associative array that a key (which matches to a value of $arr1) correspond to a value. This array may contain also keys that don't match with $arr1.
$arr2 = [1 => "foo", 2 => "foo98", 3 => "foo20", 8 => "foo02", 12 => "foo39", 15 => "foo44", 23 => "foo91", 34 => "foo77"]
I want as return the values of $arr2 specifying as key the values of $arr1:
["foo", "foo20", "foo02", "foo39", "foo91"]
If possible, all this, without loops, using just PHP array native functions (so in an elegant way), or at least with the minimum number of loops possible.
Minimal loop is simple - 1. as:
foreach($arr1 as $k) {
$res[] = $arr2[$k];
}
You can do that with array_walk but I think this simple way is more readable.
If you insist you can do with array_filter + array_values + in_array as:
$res = array_values(array_filter($arr2,
function ($key) use ($arr1) { return in_array($key, $arr1);},
ARRAY_FILTER_USE_KEY
));
You can see this for more about filtering keys
To do it purely with array functions, you could do it as...
print_r(array_intersect_key($arr2, array_flip($arr1) ));
So array_flip() turns the items you want form the array into the keys for $arr1 and then uses array_intersect_key() to match the keys with the main array and this newly created array.
Gives...
Array
(
[1] => foo
[3] => foo20
[8] => foo02
[12] => foo39
[23] => foo91
)
If you don't want the keys - add array_values() around the rest of the calls...
print_r(array_values(array_intersect_key($arr2, array_flip($arr1) )));
to get
Array
(
[0] => foo
[1] => foo20
[2] => foo02
[3] => foo39
[4] => foo91
)
Although as pointed out - sometimes a simple foreach() is just as good and sometimes better.

sorting array based on child array[0] (unix) value

I need an array sorted by Unix timestamp values. I attempted to use both ksort and krsort before realising that occasionally the timestamp values might be the same (and you cannot have duplicate keys in arrays).
Here's an example array I may be faced with:
$array = array(
[
"unix" => 1556547761, // notice the two duplicate unix values
"random" => 4
],
[
"unix" => 1556547761,
"random" => 2
],
[
"unix" => 1556547769,
"random" => 5
],
[
"unix" => 1556547765, // this should be in the 3rd position
"random" => 9
]
);
So what I'm trying to do is sort them all based on each child arrays unix value, however I cannot figure out how to do so. I have tried countless insane ways (including all other sort functions and many, many for loops) to figure it out - but to no avail.
All help is appreciated.
You can use usort which sort your array by given function
Define function as:
function cmpByUnix($a, $b) {
return $a["unix"] - $b["unix"];
}
And use with: usort($array, "cmpByUnix");
Live example: 3v4l
Notice you can also use asort($array); but this will compare also the "random" field and keep the key - if this what you need then look at Mangesh answer
array_multisort() — Sort multiple or multi-dimensional arrays
array_columns() — Return the values from a single column in the input array
You can use array_multisort() and array_column(), then provide your desired sort order (SORT_ASC or SORT_DESC).
array_multisort(array_column($array, "unix"), SORT_ASC, $array);
Explanation:
In array_multisort(), arrays are sorted by the first array given. You can see we are using array_column($array, "unix"), which means that the second parameter is the order of sorting (ascending or descending) and the third parameter is the original array.
This is the result of array_column($array, "unix"):
Array(
[0] => 1556547761
[1] => 1556547761
[2] => 1556547765
[3] => 1556547769
)
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
Note:If two members compare as equal, their relative order in the sorted array is undefined.
Refer : https://www.php.net/manual/en/function.asort.php
asort($array);
echo "<pre>";
print_r($array);
echo "</pre>";
It will give you the output as
Array
(
[1] => Array
(
[unix] => 1556547761
[random] => 2
)
[0] => Array
(
[unix] => 1556547761
[random] => 4
)
[3] => Array
(
[unix] => 1556547765
[random] => 9
)
[2] => Array
(
[unix] => 1556547769
[random] => 5
)
)
You can keep the array key [1],[0],[3],[2]) as it is Or you can keep it as sequential as per your requirement.

PHP - Sorting a multidimensional array

Array
(
[data] => Array
(
[0] => Array
(
[name] => Nicki Escudero
[id] => 27700035
)
[1] => Array
(
[name] => Yorgo Nestoridis
[id] => 504571368
)
)
)
How can I sort this multidimensional array using its name?
I tried with array_multisort but it's not working.
If you want to use array_multisort, you would use the following:
$array = array(
'data' => array(
array(
'name' => 'Yorgo Nestoridis',
'id' => 504571368,
),
array(
'name' => 'Nicki Escudero',
'id' => 27700035,
),
),
);
$names = array();
foreach($array['data'] as $datum) {
$names[] = $datum['name'];
}
array_multisort($names, SORT_ASC, $array['data']);
var_dump($array); // now sorted by name
The other choice is to use a custom comparison function:
function compareNames($a, $b) {
return strcmp($a['name'], $b['name']);
}
usort($array['data'], 'compareNames');
It is already sorted :-) What do you want to sort by? And where is the data coming from? if you get it from a DB you should sort differently.
If those are the only two values you have, you can try making id the index of the array and the name can be the value. You can then use asort to sort the array by name and maintain the index-value relation.
By making id the index, I mean $array[27700035] would return Nicki Escudero.
// Copy the array to a new array.
foreach($array as $val) {
$newArray[$val['id']] = $val['name'];
}
asort($newArray);
Edit: I've gone through the manual and you can also use usort with a custom comparison function. Although I've never used this and can be of very little help... PHP usort

Using array values as another array keys

Good day everyone.
I have an regular array (this is the print_r result, the array can have from 1 to n positions):
Array
(
[1] => value1
[2] => value2
[3] => value3
)
I have another array defined elsewhere as:
$array_def['value1']['value2']['value3'] = array(
'fl' => 'field1',
'f2' => 'field2',
);
Using the first array result, how can i check if $array_def exists? In other words, i need to use a flat array values to check if a multidimensional array correspondence exists; keep in mind that the values can repeat in the first array, therefore flipping values with keys it's not an option as it will collide and remove duplicated values.
Thanks in advance.
You can do it this way:
$a = array(1=>'value1', 2=>'value2', 3=>'value3');
$array_def[$a[1]][$a[2]][$a[3]] = array(
'fl' => 'field1',
'f2' => 'field2',
);
I don't think there's any shortcut or special built-in function to do this.
Found the perfect function for you. returns not only exists, but position within a multi-dimensional array..
http://www.php.net/manual/en/function.array-search.php#47116
dated: 03-Nov-2004 11:13
too much to copy/paste
you can then loop over your flat array and foreach:
multi_array_search($search_value, $the_array)

Categories