I have a Multilevel Array (See array structure picture below) and I need to get the sub-nested array with the higher date value.
I was wondering if there is a straight forward way to sort sub-nested arrays by date value or get the highest date value?
Array Map
To do that, usort() function will be useful:
usort($rgData, function($rgX, $rgY)
{
$x = strtotime($rgX['date']);
$y = strtotime($rgY['date']);
return $x<$y?-1:$x!=$y;
});
//var_dump($rgData);
if you want to get highest value, then it will be ['date'] key of last element after doing the sort above.
Edit: if you're sure that format will be exactly same as on picture always, you can use direct string comparison via strcmp (that would be probably faster)
How about using usort():
$input = array(
array('date' => '2013-09-11 13:08:40 +0000'),
array('date' => '2013-09-11 13:09:17 +0000'));
usort($input, function(array $a, array $b) {
$aTimestamp = strtotime($a['date']);
$bTimestamp = strtotime($b['date']);
if($aTimestamp == $bTimestamp) return 0;
return $aTimestamp < $bTimestamp;
});
print_r($input); //$input[0] has the latest date value
Related
I have array like
$a = $b = $c = [];
$a['num'] = 10;
$b['num'] = 2;
$c['num'] = 4;
$arr = array($a,$b,$c);
then now I want to order array $arr by hash ['num']
result should be array($b,$c,$a)
I think I can re-order by for loop, but it looks not cool.
I think python has list in list but is it possible in PHP?
Is there any good idea to make this??
There is no easy way to do solve this problem. Basically you have to compare the elements inside the array.
You can just use usort function with your custom comparison function.
function compare($a, $b) {
return $a['num'] - $b['num'];
}
usort($arr,"compare");
You can also give an anonymous compare function to it. If you do not plan use your custom compare function again, I recommend you to use anonymous function.
usort($arr,function($a, $b){
return $a['num'] - $b['num'];
});
Do not forget
usort function does not return an array. It just returns TRUE on success or FALSE on fail and the array that you send as a parameter will sort.
You can use sort().
sort($arr);
The inner arrays are the same length, and all have the same single key, so sort() will compare them based on their contents and $arr will be sorted as if it was simply an array of integers.
I have a multi-D array like so:
array ( 'JD'=>2457002.50, 67.618536),
array ( 'JD'=>2457003.50, 67.619705),
array ( 'JD'=>2457004.50, 67.620938)....
I have a value say:
$MyJD = 2457003.9553;
I would like to find the value in the array, and if not, match the closest number to the array in question and return the the next index (which i'm assuming is [1])
I was thinking to do an array_search, but it's not going to find the exact number, I want the closest number to $MyValue?
This won't return the index but will return the proper array:
array_multisort(array_map(function($v) use($MyJD) {
return abs($v['JD'] - $MyJD);
}, $array), $array);
$result = reset($array);
Calculate the difference between each JD value and $MyJD
Sort on the difference (sorting the original) and get the lowest (first) one
Alternately, you could combine using the difference as the key and then sort on the keys:
$array = array_combine(array_map(function($v) use($MyJD) {
return abs($v['JD'] - $MyJD);
}, $array), $array);
ksort($array);
$result = reset($array);
Maybe someone will post a good array_reduce answer.
Do bucle put new array with key difference between
In this way you will have array ordered by difference
In each iteration
$myarray[myvalue - yourvalueinbucle] if -1 this key then ×-1 and how value your enter iterator of bucle, then your value for this key = your line multiarrayvalue in for each iterator
I have a 2 dimensions array and need to sort it according to some of the second dimension values.
I tried using uksort, but it doesn't work:
$arr = array();
$arr[] = array('name'=>'test1', 'age'=>25);
$arr[] = array('name'=>'test2', 'age'=>22);
$arr[] = array('name'=>'test3', 'age'=>23);
$arr[] = array('name'=>'test4', 'age'=>29);
uksort($arr, "cmp");
print_r($arr);
function cmp($a, $b) {
if ($a['age']==$b['age']) return 0;
return ($a['age'] < $b['age']) ? -1 : 1;
}
Can anyone spot what am I doing wrong?
I think you are looking for uasort().
uksort() will order your array by keys, but you want to sort the arrays by their value.
uksort
Sort an array by keys using a user-defined comparison function
Sorting array by keys means that you take value of a key (in your case it is the same string age for all subarrays). And you sort by value.
So usort is enough - fiddle.
I have a multidimensional array in PHP where I need to remove one array based on the value of an item in one of the arrays:
Example Array
array(
"0"=>array("0"=>"joe", "1"=>"2018-07-18 09:00:00"),
"1"=>array("0"=>"tom", "1"=>"2018-07-17 09:00:00"),
"2"=>array("0"=>"joe", "1"=>"2018-07-14 09:00:00")
)
I know that I want to remove the array that contains joe in key 0, but I only want to remove the array that contains joe with the most current date in key1. The following output is what I'm trying to accomplish:
array(
"0"=>array("0"=>"tom", "1"=>"2018-07-17 09:00:00"),
"1"=>array("0"=>"joe", "1"=>"2018-07-14 09:00:00")
)
Is there a simple way to do this in PHP aside from looping through each array?
Here is a non looping method that uses array_intersect and array_column to find the "Joe's" and then deletes the maximum array_key since I first sort the array on dates.
usort($arr, function($a, $b) {
return $a[1] <=> $b[1];
}); // This returns the array sorted by date
// Array_column grabs all the names in the array to a single array.
// Array_intersect matches it to the name "Joe" and returns the names and keys of "Joe"
$joes = array_intersect(array_column($arr, 0), ["joe"]);
// Array_keys grabs the keys from the array as values
// Max finds the maximum value (key)
$current = max(array_keys($joes));
unset($arr[$current]);
var_dump($arr);
https://3v4l.org/mah6K
Edit forgot to add the array_values() if you want to reset the keys in the array.
Just add $arr = array_values($arr); after the unset.
I would go about it like this:
<?php
$foo = array(
"0"=>array("0"=>"joe", "1"=>"2018-07-18 09:00:00"),
"1"=>array("0"=>"tom", "1"=>"2018-07-17 09:00:00"),
"2"=>array("0"=>"joe", "1"=>"2018-07-14 09:00:00")
);
$tmp = [];
foreach($foo as $k => $v) {
if ($v[0] === 'joe') {
$tmp[$v[1]] = $k;
}
}
if (!empty($tmp)) {
sort($tmp); //think that is sane with date format?
unset($foo[reset($tmp)]);
}
var_dump($foo);
Not sure if you don't want to loop on principal or what... I tend to go for readability. Find all occurrences of joe. Sort on date. Remove the most recent by key.
I am creating a search capability for a forum program I'm building. At one point I have an array called searchResults which is numeric and contains 'score' as one of its dimensions (others are 'timeStarted', 'authorUID', and 'TID')
So, this array is in disarray at this point and I need to organize it to where $searchResults[1] will be the highest 'score' and [2] will have the second highest, etc. I looked at array_multisort on php.net but got rapidly lost in how it worked. So how would I sort $searchResults in numeric order (rearrange the keys) descending with a descending order of a further dimension 'sort' as the sorting mechanism? There really isn't any code to go with it but if you need a layout of how the array looks, here you go:
$searchResults:
[1] - ['timeStarted']
['authorUID']
['score'] <- Need to sort first dimension by this value descending
['TID']
etc.
Thanks for any help.
usort allows sorting by any specified comparison function
$cmp = function($a,$b) {return $b['score'] - $a['score'];};
usort($searchResults, $cmp);
In this case, $cmp is a function that compares two elements $a and $b of $searchResults based on value of ['score']. $cmp returns 0 for equality, negative val if $a['score'] is greater, positive val if $b['score'] is greater. It would normally be the other way around, but a descending sorting order is desired.
The function you want is usort. Look at example #2:
<?php
function cmp($a, $b)
{
return strcmp($a["fruit"], $b["fruit"]);
}
$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";
usort($fruits, "cmp");
while (list($key, $value) = each($fruits)) {
echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>
The output:
$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons