How to sort 2 arrays by the value [duplicate] - php

This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 7 years ago.
I have this array:
Array (
[order] => Array ( [0] => 2 [1] => 1 )
[eventid] => Array ( [0] => id_1 [1] => id_2 )
)
Now I would like to get:
Array (
[order] => Array ( [0] => 1 [1] => 2 )
[eventid] => Array ( [0] => id_2 [1] => id_1 )
)
Basically I would like to sort arrays by value of order.

You will need to use the usort function to be able to do this. (See the documentation)
I would recommend another Array structure though, something like this:
Array (
[0] => Array ( [order] => 2, [eventid] => id_x )
[1] => Array ( [order] => 1, [eventid] => id_y )
)
Then you could a function like this one to sort your array (PHP 5.3 or greater):
function array_sort_by(&$array, $key, $descending = false) {
$sortByKey =
function ($a, $b) use ($key, $descending) {
if ($a[$key] === $b[$key]) {
return 0;
}
$return = $a[$key] < $b[$key] ? -1 : 1;
return ($descending ? -1 * $return : $return);
};
usort($array, $sortByKey);
}
You would then call the following:
array_sort_by($yourArray, 'order');

You can use asort. While it can cover your case, usort might be a better solution in the long run.
$arr = Array (
"order" => Array ( 0 => 6, 1 => 1,2=>43),
"eventid" => Array ( 0 => 5, 1 => 1,2=>54,3=>0)
);
foreach ($arr as $key => &$value) {
asort($value);
}

Related

Merge values from different arrays to one with the same key [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 10 months ago.
I have two arrays:
Array
(
[0] => 5
[1] => 4
)
Array
(
[0] => BMW
[1] => Ferrari
)
And I would like to have that result. Merge the values with the same key
Array
(
[0] => Array
(
[0] => 5
[1] => BMW
)
[1] => Array
(
[0] => 4
[1] => Ferrari
)
)
How could I do that? Is there any native PHP function that does this? I tried array_merge_recursive and array_merge but did not get the expected result
As to #splash58 comment:
You can use array-map. Here an example:
$array = [["5", "4"], ["BMW", "Ferrari"]];
$res = array_map(null, ...$array);
Now res will contain:
Array
(
[0] => Array
(
[0] => 5
[1] => BMW
)
[1] => Array
(
[0] => 4
[1] => Ferrari
)
)
If the array in 2 different var you can use:
$res= array_map(null, ["5", "4"], ["BMW", "Ferrari"]);
<?php
$a = array();
$a[0] = '5';
$a[1] = '4';
$b = array();
$b[0] = 'BMW';
$b[1] = 'Ferrari';
merge_by_key($a, $b);
function merge_by_key($a, $b){
$c = array();
fill_array($c,$a);
fill_array($c,$b);
print_r($c);
}
function fill_array(&$c, $a) {
foreach ($a as $key => $value){
if(isset($c[$key])) {
array_push($c[$key], $value);
} else {
$c[$key] = array($value);
}
}
}
Output:
Array
(
[0] => Array
(
[0] => 5
[1] => BMW
)
[1] => Array
(
[0] => 4
[1] => Ferrari
)
)
You can use array_map with null as the first argument (there is an example in the manual), to get your desired result:
<?php
$nums = [0 => 5, 1 => 4];
$cars = [0 => 'BMW', 1 => 'Ferrari'];
var_export(array_map(null, $nums, $cars));
Output:
array (
0 =>
array (
0 => 5,
1 => 'BMW',
),
1 =>
array (
0 => 4,
1 => 'Ferrari',
),
)
Note that the following input would give the same result:
$nums = ['puff' => 5, 'powder' => 4];
$cars = ['powder' => 'BMW', 'puff' => 'Ferrari'];
It is the order, not the keys, that determine the pairings in the result when using array_map as above.
To associate by key using foreach (note order of $cars):
<?php
$nums = [0 => 5, 1 => 4];
$cars = [1 => 'Ferrari', 0 => 'BMW'];
foreach($nums as $k => $num)
$result[] = [$num, $cars[$k]];
var_export($result);
Results also in the desired output.

Sort array by name with array key [duplicate]

This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 4 years ago.
I have an array like this, how can I sort by "name"
Array (
[0] => Array (
[id] => 1
[name] => status_category_confide
)
[1] => Array (
[id] => 2
[name] => status_category_love
)
[2] => Array (
[id] => 3
[name] => status_category_household
)
[3] => Array (
[id] => 4
[name] => status_category_family
)
[4] => Array (
[id] => 5
[name] => status_category_friends
)
[5] => Array (
[id] => 6
[name] => status_category_colleague
)
[6] => Array (
[id] => 7
[name] => status_category_work
)
[7] => Array (
[id] => 8
[name] => status_category_ambition
)
)
I've tried using the "sort" function but it doesn't work
$get_status_mood=mysqli_query($con, "select id, name from category");
while ($gsm=mysqli_fetch_array($get_status_mood)) {
//array_push($status_category, constant($gsm['name']));
$status_category[] = array(
"id"=>$gsm['id'],
"name"=>$gsm['name']
);
}
sort($status_category);
for ($i=0; $i<count($status_category); $i++) {
echo"<option value='".$status_category[$i]['id']."'>".$status_category[$i]['name']."</option>";
}
I want to display the results in the order of the name
Try the SQL order by option
$get_status_mood=mysqli_query($con, "select id, name from category order by name asc");
You can sort it using array_column and array_multisort functions.
$keys = array_column($array, 'name');
array_multisort($keys, SORT_ASC, $array);
You can try it with usort this sort an array by values using a user-defined comparison function
function cmp($a, $b)
{
return strcmp($a["name"], $b["name"]);
}
usort($vc_array, "cmp");
$a = array();
$a[] = array('id' => 1, 'name' => 'status_category_confide');
$a[] = array('id' => 2, 'name' => 'status_category_love');
$a[] = array('id' => 3, 'name' => 'status_category_household');
function cmp($x, $y) {
if (strcmp($x['name'], $y['name']) == 0) {
return 0;
}
return (strcmp($x['name'], $y['name']) < 0) ? -1 : 1;
}
usort($a, "cmp");
print_r($a);

How do I sort a multidimensional array? [duplicate]

This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 5 years ago.
I'm tracking how many words appear in the description of my products and created a multidimensional array that is keeping track but I need to sort them by the most found keywords to the lowest. I have this array and I want to be able to sort it by the "count" key:
Array
(
[KOM1-K182924DA] => Array
(
[count] => 1
[words] => Array
(
[4] => cotton
)
)
[PVH1-U2666001] => Array
(
[count] => 2
[words] => Array
(
[2] => cotton
[5] => briefs
)
)
[GEO2-K2345TF] => Array
(
[count] => 1
[words] => Array
(
[4] => red
)
)
[KOM1-K182871HK] => Array
(
[count] => 3
[words] => Array
(
[4] => cotton
[5] => nylon
[6] => blue
)
)
)
So the result would look like this:
Array
(
[KOM1-K182871HK] => Array
(
[count] => 3
[words] => Array
(
[4] => cotton
[5] => nylon
[6] => blue
)
)
[PVH1-U2666001] => Array
(
[count] => 2
[words] => Array
(
[2] => cotton
[5] => briefs
)
)
[KOM1-K182924DA] => Array
(
[count] => 1
[words] => Array
(
[4] => cotton
)
)
[GEO2-K2345TF] => Array
(
[count] => 1
[words] => Array
(
[4] => red
)
)
)
How can I do this? I've tried multiple solutions that I found on stackoverflow but none of them have worked for me. I've tried the solution on here Sort Multi-dimensional Array by Value. I'm using PHP 5.6 so I tried this:
usort($myArray, function($a, $b) {
return $a['order'] - $b['order'];
});
But it's not returning an array, instead it returns the "sku" and a digit.
Extract the count column into a single dimension, sort that descending and sort the original array by that:
array_multisort(array_column($myArray, 'count'), SORT_DESC, $myArray);
you may use array_multisort or usort
working solution:
function sortBySubValue($array, $value, $asc = true, $preserveKeys = false)
{
if ($preserveKeys) {
$c = array();
if (is_object(reset($array))) {
foreach ($array as $k => $v) {
$b[$k] = strtolower($v->$value);
}
} else {
foreach ($array as $k => $v) {
$b[$k] = strtolower($v[$value]);
}
}
$asc ? asort($b) : arsort($b);
foreach ($b as $k => $v) {
$c[$k] = $array[$k];
}
$array = $c;
} else {
if (is_object(reset($array))) {
usort($array, function ($a, $b) use ($value, $asc) {
return $a->{$value} == $b->{$value} ? 0 : ($a->{$value} - $b->{$value}) * ($asc ? 1 : -1);
});
} else {
usort($array, function ($a, $b) use ($value, $asc) {
return $a[$value] == $b[$value] ? 0 : ($a[$value] - $b[$value]) * ($asc ? 1 : -1);
});
}
}
return $array;
}
sortBySubValue($array, 'count', false, true);

How do I sort an array by a specific value inside of it? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sorting an array based on its value
I want to sort an array by a value inside of it. I tried usort but it leads to some unexpected results in actually changing the value of the output instead of just shifting elements in the array.
Below is the array I want to sort:
Array
(
[element1] => Array
(
[Total] => 1
[paTotal] => 0
[totalPreregistrations] => 7
[totalPreregistrationsToDate] => 26
[pas] => Array
(
[0] => Array
(
[id] => 119
)
)
)
[element2] => Array
(
[Total] => 1
[paTotal] => 0
[totalPreregistrations] => 0
[totalPreregistrationsToDate] => 58
[pas] => Array
(
[0] => Array
(
[id] => 107
)
)
)
... element3, 4, etc...
I want to sort by the "totalPreregistrations" number so that element2 goes above element1 if element2's totalPreregistrations count goes above element1's.
And of course I want the sub-arrays to be retained as well.
Thank you!
Documentation: uasort()
function mySort($a, $b) {
if( $a['totalPreregistrations'] == $b['totalPreregistrations'] ) {
return 0;
} else if( $a['totalPreregistrations'] > $b['totalPreregistrations'] ) {
return 1;
} else {
return -1;
}
}
uasort($array, 'mySort');
You can use uasort instead of usort
uasort($array, function ($a, $b) {
$a = $a['totalPreregistrations'];
$b = $b['totalPreregistrations'];
return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);
});
echo "<pre>";
print_r($array);
Output
Array
(
[element2] => Array <-------------------------- element key remains intact
(
[Total] => 1
[paTotal] => 0
[totalPreregistrations] => 0
[totalPreregistrationsToDate] => 58
[pas] => Array
(
[0] => Array
(
[id] => 107
)
)
)
[element1] => Array
(
[Total] => 1
[paTotal] => 0
[totalPreregistrations] => 7
[totalPreregistrationsToDate] => 26
[pas] => Array
(
[0] => Array
(
[id] => 119
)
)
)
)

Searching for a key in a multidimensional array then changing a value with PHP

I have a multidimensional array that looks like this
[0] => Array
(
[recordId] => 5
[leaf] => 1
[children] => Array
(
[0] => Array
(
[recordId] => 6
[leaf] => 1
[children] => Array
(
[0] => Array
(
[recordId] => 7
[leaf] => 1
)
)
)
[1] => Array
(
[recordId] => 8
[leaf] => 1
[children] => Array
(
[0] => Array
(
[recordId] => 9
[leaf] => 1
)
[1] => Array
(
[recordId] => 10
[leaf] => 1
)
)
)
)
)
Each node has a 'leaf' key that is TRUE by default and has a 'children' array if there are further nodes down.
I need to set the 'leaf' key value to FALSE if there is a 'children' array contained in the node. That way only final nodes have the leaf = TRUE designation.
I've tried searching but can't find code to do what I need and I can't wrap my head around the recursive function that I believe is needed.
Any ideas how I could accomplish this in PHP?
Thanks for the help.
In theory this should work:
function findChild(&$array){
foreach($array as &$arr){
if(isset($arr['children'])){
$arr['leaf'] = 0; //there are children
findChild($arr['children']);
}
else {
$arr['leaf'] = 1; //there are no children
}
}
}
Here is a working demo: http://codepad.org/AnYiRpES
Pretty simple actually:
function leafOrNotLeaf(array $array) {
foreach ($array as $key => $sub) {
if (isset($sub['children'])) {
$array[$key]['leaf'] = false;
$array[$key]['children'] = leafOrNotLeaf($sub['children']);
}
}
return $array;
}
$new_array = leafOrNotLeaf($array);
Walking on the actual $array:
array_walk($array, $walker = function (&$node) use (&$walker) {
$node['leaf'] = (int) empty($node['children'])
OR array_walk($node['children'], $walker);
});
A bit cryptic maybe, so you gotta love PHP.

Categories