I'm a very beginner php worker who just got to know Stackoverflow.
My requirement is to select the largest value inside the nested array. Let me explain with an example.
$arr = [
["id"=>1],
["id"=>2],
["id"=>2],
["id"=>2],
["id"=>3],
["id"=>4],
["id"=>4],
["id"=>4]
];
In this array, we have the number 2 and 4, which are repeated the most.
What functions can I use to do this?
CodePudding user response:
You can do something like this:-
<?php
$arr = [
["id"=>1],
["id"=>2],
["id"=>2],
["id"=>2],
["id"=>3],
["id"=>4],
["id"=>4],
["id"=>4]
];
$repeatedArr = array();
foreach($arr as $key => $data) {
foreach($data as $id => $value) {
if(array_key_exists($value, $repeatedArr)) {
$repeatedArr[$value] ;
} else {
$repeatedArr[$value] = 1;
}
}
}
foreach($repeatedArr as $key => $value) {
echo $key . " is repeated " . $value . " times\r\n";
}
CodePudding user response:
This would be an approach:
<?php
$data = [
["id"=>1],
["id"=>2],
["id"=>2],
["id"=>2],
["id"=>3],
["id"=>4],
["id"=>4],
["id"=>4]
];
$counts = [];
array_walk($data, function($entry) use (&$counts) {
$counts[$entry["id"]] ;
});
var_dump($counts);
The output obviously is:
Array
(
[1] => 1
[2] => 3
[3] => 1
[4] => 3
)
CodePudding user response:
You can leverage array_count_values.
<?php
$data = [
["id"=>1],
["id"=>2],
["id"=>2],
["id"=>2],
["id"=>3],
["id"=>4],
["id"=>4],
["id"=>4]
];
$ids = array_column($data, 'id', null);
$id_counts = array_count_values($ids);
$max_ids = array_keys($id_counts, max($id_counts));
var_export($max_ids);
Output:
array (
0 => 2,
1 => 4,
)
CodePudding user response:
As you asked to "select the largest value"...
If you want to return the array holding the largest value...
max($arr)
will return ["id"=>4]
If you want only the value returned...
array_values(max($arr))[0]
will return (int)4