How to get "maximum range" from an array - php

Index is 00 to 23 (24-hour time)
What I am trying to accomplish is to get largest maximum range.
Each array will have a maximum of 24 elements. Of these, I want to get all the ones which are high (a range).
So,
for first array - 10,16,19,19
second - 18,19,20
third - 9,11.
Array
(
[00] => 10
[01] => 19
[02] => 10
[03] => 4
[04] => 1
[13] => 16
[14] => 2
[15] => 5
[16] => 2
[17] => 3
[18] => 1
[19] => 1
[20] => 1
[21] => 5
[22] => 1
[23] => 2
)
Array
(
[09] => 6
[10] => 20
[11] => 18
[12] => 19
[13] => 3
[15] => 11
[16] => 9
[18] => 10
)
Array
(
[00] => 4
[01] => 3
[12] => 4
[16] => 4
[21] => 9
[22] => 11
[23] => 6
)
The problem is, these values could get changed entirely, like this one -
Array
(
[13] => 117
[14] => 221
[15] => 211
[16] => 145
[17] => 23
[18] => 15
[19] => 1
)
Any solution for this?
Thank you,people.

It's a bit unclear how you want to choose which values are 'high', but:
In PHP 5.3+
$filetered = array_filter($yourArray, function($v) {return $v > 10;});
Will return array with values higher than 10.
In PHP <5.3 you will need to createa callback function instead of passing a closure to array_filter.

Use array_keys() and than max() to get the maximum key value:
$keys = array_keys($myArray);
$maxKey = max($keys);

I think what you want (although it's not very clear what is a "high" value) can be accomplished with asort(). If you sort your array numerically:
asort($yourarray, SORT_NUMERIC);
Then you can just retrieve the first elements from the sorted array. You don't even specify how many elements should be retrieved, but I'm guessing it's 3, although you don't seem to want anything below 10, so just use array_slice() to extract the last three elements and if any of them is lower than 10 discard it.
Putting it all together would give something like:
asort($yourarray, SORT_NUMERIC);
$top3 = array_slice($yourarray, -3, null, true)
$filtered = array_filter($top3, function($v) {return $v > 10;});
Note: I used Mchl example on the final part of my answer.

You can use array_filter() to filter out those values that are not within the range:
function is_between_10_and_20($v)
{
return ($v >= 10 && $v <= 20);
}
$result = array_filter($arr, "is_between_10_and_20")

Related

What is the best approach to create an array having specific key's value from a multidimensional array? [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 7 months ago.
Hello i have an multidimensional array
each of the array contains key of "id_category"
I am trying to store value of key "id_category" while loop through the multidimensional array.
Here is the array & php compiler
https://paiza.io/projects/H8FwXLAZc438-XA-hnmNHQ?language=php
$save_id_category = [];
foreach($array as $ct){
$save_id_category[] = $ct['id_category'];
}
print_r($save_id_category); // this gets me only one record.
I can loop through all array & save data but that would be not good idea.
Please let me know if we have a better approach
for this.
Thanks
You can use a recursive function to find all the id_category values, first getting all the values at the current level using array_column, then iterating over the children of each array element to add their categories to the list:
function get_categories($array) {
$categories = array_column($array, 'id_category');
foreach ($array as $ct) {
$categories = array_merge($categories, get_categories($ct['children'] ?? array()));
}
return $categories;
}
print_r(get_categories($arrayone));
Output (for your sample data):
Array
(
[0] => 12
[1] => 13
[2] => 15
[3] => 16
[4] => 48
[5] => 68
[6] => 58
[7] => 282
[8] => 17
[9] => 18
[10] => 85
[11] => 52
[12] => 53
[13] => 86
[14] => 54
[15] => 55
[16] => 56
[17] => 217
[18] => 275
[19] => 69
[20] => 70
[21] => 71
[22] => 278
[23] => 59
[24] => 60
[25] => 61
[26] => 283
)

How to store 3 key by index per row PHP [duplicate]

This question already has an answer here:
Multi dimensional loops from 4 existing arrays [duplicate]
(1 answer)
Closed 10 months ago.
i have problem with array, i have 3 array and i wont to merge into one by row index
$tahun = array(2010,2011,2012,2013,2014);
$status = array("akademi","instansi","umum","pending","pass");
$total = array(2,1,3,4,5);
i want this array into want like this
array(
0 => array(2010,"akademi",2),
1 => array(2011,"instansi",1),
2 => array(2012,"umum",3),
3 => array(2013,"pemding",4),
4 => array(2014,"pass",5),
);
but when i use array_merge_recursive() the output like this
Array
(
[0] => 2015
[1] => 2016
[2] => 2017
[3] => 2018
[4] => 2019
[5] => 2019
[6] => 2019
[7] => 1
[8] => 1
[9] => 1
[10] => 1
[11] => 3
[12] => 2
[13] => 1
[14] => akademisi
[15] => instansi pemerintah
[16] => umum
[17] => umum
[18] => akademisi
[19] => instansi pemerintah
[20] => umum
)
You can use array_map() with null as the callback...
$combined = array_map(null, $tahun, $status, $total);
from the manual...
NULL can be passed as a value to callback to perform a zip operation
on multiple arrays. If only array1 is provided, array_map() will
return the input array.
Use simple foreach loop:
$res = [];
foreach($tahun as $ind=>$val){
$res[$ind] = [$val, $status[$ind], $total[$ind]];
}
Demo

PHP: uasort not working [duplicate]

This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 11 months ago.
I have the following array
$infoArray = Array
(
[Shockwafe Ultra 9.2] => Array
(
[0] => 8
[1] => 45 Hz - 18.000 Hz
[2] => 9.2
[3] => 1
[4] => 1
[5] => 1
[6] =>
[7] =>
[8] => B+
[9] => B+
[10] => A
[11] => B
)
[Bose 5.1 SoundTouch 300] => Array
(
[0] => 9
[1] => 45 Hz - 20.000 Hz
[2] => 5.1
[3] => 1
[4] => 1
[5] => 1
[6] => 1
[7] => 1
[8] => A
[9] => A
[10] => A+
[11] => A+
)
[Sonos 5.1 System] => Array
(
[0] => 10
[1] => 31.5 Hz - 20.000 Hz
[2] => 5.1
[3] => 1
[4] => 1
[5] => 1
[6] => 1
[7] => 1
[8] => A+
[9] => A+
[10] => A+
[11] => A+
)
)
I am trying to sort it with the use of PHP. I want to sort by the [0] value in each array member. So the order should be, Sonos first, Bose second, Shockwafe third.
My PHP code looks as following:
function sortByOrder($a, $b) {
return $a[0] - $b[0]; }
uasort($infoArray, 'sortByOrder');
I've tried this on wamp, where it succesfully arranges the order like i'd want. However, online in my Wordpress installation, this does NOT work. It simply does not re-arrange the array. It should be noted, that I am working inside functions.php within a shortcode. I tried moving the sortByOrder() function outside of the shortcode area, with no success.
Any ideas what goes wrong?
function sortByOrder($a, $b) {
$result = 0;
if ($b['rating'] > $a['rating']) {
$result = 1;
} elseif ($b['rating'] < $a['rating']) {
$result = -1;
}
return $result;
}
This ended up being my solution. It has something to do with decimal numbers, I'm not exactly sure why it worked. Solution in OP is fine if you work with whole numbers, but this is required for decimal numbers.
Ran into the same issue. Turns out the comparison callback is expected to return an integer value. If you return a float, your value will be casted to an int. This means that values between -1 and 1 all become 0. That's why whole numbers work: the difference between them is always at least 1 if they aren't the same.
PHP 7.4 introduced arrow functions and the "spaceship operator". Those make comparator functions very concise. Ordering "by rating" would therefore be:
uasort($infoArray, fn($a, $b) => $a['rating'] <=> $b['rating']);

PHP descending an array stored from foreach loop values

i have a foreach loop like this
$ids = array();
foreach( $idsvalues as $idv ){
$ids[$idv->id][] = $idv->value;
}
and i get an array like this
Array ( [21] => 10 [13] => 16 [12] => 20 [7] => 28 )
now how do i descending this array() values only from lowest to highest without effecting the array keys or id?
to show like this
Array ( [21] => 28 [13] => 20 [12] => 16 [7] => 10 );
the array can contain upto 100 such ids and values so basically just descending the values?
Since you want to preserve the keys, transfer them to a separate array by using array_keys now rsort your array (i.e. descending order) , Make use of array_combine to link the grabbed keys and descending sorted values.
<?php
$arr=Array ( 21 => 10, 13 => 16, 12 => 20, 7 => 28 );
$k_arr=array_keys($arr);
rsort($arr);
$new_arr=array_combine($k_arr,$arr);
print_r($new_arr);
Output:
Array
(
[21] => 28
[13] => 20
[12] => 16
[7] => 10
)
Demo

Re-order PHP array by middle key as start (Circular Sorting)

very basic question however I have had some trouble finding the answers on PHP.NET.
I have the following array:
Array (
[1] => Array
(
[1] => 4
[2] => 1
[3] => 5
[4] => 3
)
[2] => Array
(
[5] => 2
[6] => 8
[7] => 7
[8] => 6
)
[3] => Array
(
[9] => 10
[10] => 9
[11] => 12
[12] => 11
)
[4] => Array
(
[13] => 15
[14] => 16
[15] => 14
[16] => 13
)
)
I want the array to be re-ordered so that the key number 3 in the first series of the array becomes the first, then the rest to be re-ordered from there to eventually get the result of:
Array (
[3] => Array
(
[9] => 10
[10] => 9
[11] => 12
[12] => 11
)
[4] => Array
(
[13] => 15
[14] => 16
[15] => 14
[16] => 13
)
[1] => Array
(
[1] => 4
[2] => 1
[3] => 5
[4] => 3
)
[2] => Array
(
[5] => 2
[6] => 8
[7] => 7
[8] => 6
)
)
I am looking for a way to do this so I can define the array, then the first level key I need to sort by, and then it will return the array in this way.
The standard PHP keys didn't seem to offer something like this, so it would be good to be able to have a separate function such as $newArray = reorder_array($array, $key);
I don't require any sorting of the second level, only the initial 4 main / first level array sections.
You help is greatly appreciated as I have been sitting on this one for awhile without a clear and simple solution.
You re-ordering can be simply implemented with one foreach loop, like:
function reorderArray($array, $key)
{
$found = false;
foreach($array as $k=>$v)
{
$found = $found || $k===$key;
if(!$found)
{
unset($array[$k]);
$array[$k] = $v;
}
//else break can be added for performance issues
}
return $array;
}
with usage
$array=[1=>'foo', 4=>'bar', 9=>'baz', 'test'=>51];
var_dump(reorderArray($array, 9));
var_dump(reorderArray($array, 'test'));
var_dump(reorderArray($array, 'no_such_key'));//original array in result
-check this demo. If keys are consecutive numerics, however, this can be easily implemented with array_slice() calls.

Categories