How do I order an array that contains arrays? [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Sort an array by a child array's value in PHP
I have the following array structure:
$en_array = array();
while(...) {
$en_array[] = $row;
}
$en_array = array (
array (
"name" => "a",
"followers" => 5,
"imageurl" => "http://images.com/img.jpg"
)
array (
"name" => "b",
"followers" => 25,
"imageurl" => "http://images.com/img.jpg"
)
array (
"name" => "c",
"followers" => 15,
"imageurl" => "http://images.com/img.jpg"
)
)
In this example I would like to order the keys of en array by the values of followers, e.g. $en_array[0]["followers"] would have the value of 25.
I'm not entirely sure if this can be done, but I hope it can.
Any help will be much appreciated :)!!

Since it looks like you're only interested in sorting by followers, we can do this easily with PHP's usort.
function compare_by_followers($a, $b) {
if($a['followers'] == $b['followers']) return 0;
return $a['followers'] > $b['followers'] ? -1 : 1;
}
usort($en_array, 'compare_by_followers');
Sorting is, at its core, a process of comparing the array's elements to each other and figuring out which ones are greater than the others. usort allows you to use a custom comparison function for this process: compare_by_followers($a, $b) returns -1 if $a['followers'] is greater than $b['followers'] (meaning that $a should go before $b), returns 1 if $a['followers'] is less than $b['followers'] (meaning that $a should come after $b), and returns 0 if they are equal.

array_multisort() is what you are after.
foreach ($en_array as $key => $row) {
$name[$key] = $row['name'];
$followers[$key] = $row['followers'];
}
array_multisort($followers,SORT_DESC,$name,SORT_ASC,$en_array);
After this, results are in descending order of followers, and where followers are the same, ascending order of name (i.e. alphabetical order).

Related

Combine value of unique keys in array [duplicate]

This question already has answers here:
PHP Associative Array Duplicate Keys
(6 answers)
Closed 8 months ago.
I am a complete newbie at programming and am trying to create a function that combines the values of unique keys and then returns the highest value.
$arr = array(
"Canada"=>500,
"US"=>2,
"Mexico"=>40,
"Mexico"=>50,
"US"=>170,
"Canada"=>25,
"Mexico"=>5,
"US"=>300
);
Right now, if I print out the array, I get:
Array ( [Canada] => 25 [US] => 300 [Mexico] => 5 )
I want it to print out the following:
Canada = 525
I've tried during foreach loops, array_sum, array_map, array_reduce, but to no avail :(
As arrays always have unique keys I recommend you re-format your input array to an array of arrays like so
$arr = array(
array("Canada"=>500),
array("US"=>2),
array("Mexico"=>40),
array("Mexico"=>50),
array("US"=>170),
array("Canada"=>25),
array("Mexico"=>5),
array("US"=>300)
);
You can then parse this array in a loop - adding the values t0 $counter_array
$counter_array = array();
foreach ($arr as $arrays) {
foreach ($arrays as $key => $value) {
if (!isset($counter_array[$key])) {
$counter_array[$key] = 0;
}
$counter_array[$key] += $value;
}
}
print_r($counter_array);
Array
(
[Canada] => 525
[US] => 472
[Mexico] => 95
)
Array Data Structure require unique identifier for each value. It's due to the way it's stored in memory.
Ask yourself: How would program distinguish between the two keys?
In your example. Let's say I'm trying to fetch a value of $arr["Canada"].
You put 2 different values to that identifier (key). Logically, the last one will override the previous one. And that is what exactly will happen if you will try to instantiate this array.
In this case I would change the way of array instantiation to make it something like this:
$arr = [
"Canada" => [500, 25],
"US" => [2, 170, 300],
"Mexico" => [40, 50, 5]
];
$result = array_map(function ($e) {
return array_sum($e);
}, $arr);
var_export($result);
array ( 'Canada' => 525, 'US' => 472, 'Mexico' => 95)

PHP array sort with forced the first row [duplicate]

This question already has answers here:
Move array item with certain key to the first position in an array, PHP
(9 answers)
move array element to the first position but remain order
(4 answers)
Move an array element to a new index in PHP
(9 answers)
Move Value in PHP Array to the Beginning of the Array
(12 answers)
Move array element with a particular value to top of array
(2 answers)
Closed 2 months ago.
How to sort an array at PHP to force selected row as a first ?
My array is
array[]=array(id=>'a', content=>'lemon');
array[]=array(id=>'b', content=>'apple');
array[]=array(id=>'c', content=>'banana');
array[]=array(id=>'d', content=>'cherry');
How to sort the array to force
array[]=array(id=>'b', content=>'apple');
as a first row and doesn't matter the rest (apple is the key).
And in other example turn sort to get
array[]=array(id=>'d', content=>'cherry');
as a first row and doesn't matter the rest (cherry is the key).
Another way to do this is to effectively rotate the array using array_slice, bringing the element you want to the start:
$first = 'apple';
$k = array_search($first, array_column($array, 'content'));
$array = array_merge(array_slice($array, $k), array_slice($array, 0, $k));
print_r($array);
Output:
Array (
[0] => Array ( [id] => b [content] => apple )
[1] => Array ( [id] => c [content] => banana )
[2] => Array ( [id] => d [content] => cherry )
[3] => Array ( [id] => a [content] => lemon )
)
Demo on 3v4l.org
There are 2 ways I can think of doing this. The first is as Ultimater in the comments suggest to extract the matching row, then sort and then add the row back in...
$first = 'apple';
$array = [];
$array[]=array('id'=>'a', 'content'=>'lemon');
$array[]=array('id'=>'b', 'content'=>'apple');
$array[]=array('id'=>'c', 'content'=>'banana');
$array[]=array('id'=>'d', 'content'=>'chery');
$firstElement = array_search($first, array_column($array, "content"));
$row = $array[$firstElement];
unset($array[$firstElement]);
sort($array);
array_unshift($array, $row);
print_r($array);
The second is to use usort and add specific clauses in that if the key matches the row you want first, then it will always force it to the first row...
$first = 'apple';
usort($array, function ($a, $b) use ($first){
if ( $a['content'] == $first) {
return -1;
}
if ( $b['content'] == $first) {
return 1;
}
return $a <=> $b;
});
print_r($array);
(I've used <=> in this which is PHP 7+, there are alternatives if you need to use PHP 5).
If as your comment suggests that there is no need to sort the rest of the data, then the first set of code minus the sort() should do.
One other option - if id:content is one to one, we can index the array by content and merge with an array with a single empty "apple" key (or whichever content value you're looking for).
$array = array_merge(['apple' => []], array_column($array, null, 'content'));
If the resulting string keys are undesirable the array can be reindexed with array_values.
If the array only contains id and content and id:content is in fact one to one, a "dictionary" of key-value pairs will be handier to deal with than a list of rows like this and it would probably be better to set the array up that way to begin with if possible.
If id:content is not one to one, then... never mind. ;-)

PHP: How to sort array by value first, then by key [duplicate]

This question already has answers here:
Sort a flat, associative array by numeric values, then by non-numeric keys
(8 answers)
Closed 2 years ago.
I've been breaking my head over the following problem.
I've got this array:
[596] => 2
[9] => 2
[358] => 2
[1579] => 1
[156] => 1
[576] => 1
[535] => 1
As you can see, the values are ordered in a descending way, but the keys are random. I would like to keys to be sorted DESC as well though. I've been playing with array_multisort, but I haven't been able to fix the problem with it. The first problem that I encountered was the fact that array_multisort reindexes numeric keys. I changed to keys to a non-numeric variant, namely k596 etc... That made me able to sort the keys, but not like I wanted it to.
[k9] => 2
[k596] => 2
[k358] => 2
[k576] => 1
[k535] => 1
[k1579] => 1
[k156] => 1
The result that I would like to see in the end is:
[k596] => 2
[k358] => 2
[k9] => 2
[k1579] => 1
[k576] => 1
[k535] => 1
[k156] => 1
Is anyone able to help me out here? There must be a simple way to do this, right?
uksort($array, function ($a, $b) use ($array) {
if ($array[$a] != $array[$b]) {
return $array[$a] - $array[$b];
}
return $a - $b;
});
Insert appropriate comparison operations, using simply - here as an example. This is somewhat trickier if you're dependent on PHP < 5.3 and don't have anonymous functions.
Ok this question is a bit more tricky then I thought! Given an array $arry = array('a'=>'hilbert', 'b'=>'noether', 'c'=>'landau');
I would generate a second array containing tuples like this:
$brry = array();
foreach($arry as $key => $value){
$brry[] = array($key,$value);
}
//Now $brry looks like:
//$brry:
// [0] => array('a','hilbert');
// [1] => array('b','noether');
// [2] => array('c','landau');
//now you can easily sort it!
usort($brry, "cmp");
//And then transform it back to the array structure you have before
foreach($brry as $value){
$crry[$value[0]] = $value[1];
}
//with this sorting function cmp:
function cmp($first, $second){
if(strcmp($first[1], $second[1]) != 0){
return strcmp($first[1], $second[1]);
}
else{
return strcmp($first[0], $second[0]);
}
}
The function cmp sorts by strings now so strcmp("192","20") > 0 while this might not be true for integers!

Php Sorting arrays

I have a key => value array:
a => 2
c => 1
b => 3
I tried this:
ksort($result);
arsort($result);
But it doesn't work. I'm trying to sort by key alphabetically a-z and then sort it by value ascending 0-infinity.
so I should get
c => 1
a => 2
b => 3
But those sorts didn't give me what I wanted.
Try using asort() instead of arsort(). arsort() will sort the array in reverse order. Something like this should "work":
$test = array(
'a' => 0,
'b' => 1,
'c' => 2
);
ksort($test);
asort($test);
Mario is correct that this won't work if multiple items contain the same value. Alternatively, you could use uksort() which allows you to define exactly how the array is sorted. For example you could sort two items using their values by default. But if the values are the same sort by their keys.
$test = array(
'a' => 2,
'd' => 1,
'c' => 1,
'b' => 3
);
function cmp($a, $b){
global $test;
$val_a = $test[$a];
$val_b = $test[$b];
if($val_a == $val_b){
return ($a < $b) ? -1 : 1;
}
return ($val_a < $val_b) ? -1 : 1;
}
uksort($test, 'cmp');
I get unexpected results because sorting values that have the same value is unstable.
So what you forgot to mention in your question is that values can occur twice, and you want arrays sorted by values and keys secondarily.
c => 1
a => 2
z => 2
b => 3
There's no function for that in PHP. You could however try to sort by keys first ksort(), and then apply a user-defined function for sorting by value uasort(). In the callback it's important to also implement the $a == $b check and return 0. So the previous key-ordering might not be accidentally altered by +1 or -1 comparison states. (Don't know if that actually works.)
Otherwise you'll have to implement the whole sorting algorithm yourself, possibly separating keys and values in distinct maps.

How to sort an array in array by a specific key in PHP [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Sorting an associative array in PHP
How to sort a multidimensional array by a certain key?
I would like to know how can I sort an array in array by a specific key.
For example:
$array = array( 0 => array("id"=>25), 1 => array("id"=>15) , 2 => array("id"=>19) );
now I want to sort the array by the key "id", i'm expecting this result:
$array = array( 0 => array("id"=>15), 1 => array("id"=>19) , 2 => array("id"=>25) );
Anybody can help ?
Thanks
Hope this may work.
function cmp($a, $b){
return $a['id'] - $b['id'];
}
usort($array, 'cmp');

Categories