[英]Find for each sub array in multidimensional array, if element on fixed position is highest value for this sub array
Hello all.大家好。
For each sub array in $arr_rgb (Fig.01) I have to find: If element with $key number 1 is the highest number in this sub array, then return the $key number of the sub array (Fig.03 and Fig.04. So far, I can find highest number for each sub array – fig.02对于 $arr_rgb 中的每个子数组(图 01),我必须找到: 如果 $key 编号为 1 的元素是此子数组中的最高编号,则返回子数组的 $key 编号(图 03 和图 03)。 04. 到目前为止,我可以找到每个子数组的最大数字 - 图 02
In the attached image the "trouble" I have is explained.在附图中解释了我遇到的“麻烦”。
And the code that I use so far:到目前为止我使用的代码:
<?php
$hex_splited = [
['00','00','00'],
['10', '11', '10'],
['F0', '1A', 'C3'],
['0F', 'FE', 'F4'],
];
$arr_rgb = [];
$count2 = count($hex_splited);
for ($i=0; $i < $count2; $i++) {
$inn_count = count($hex_splited[$i]);
for ($j=0; $j < $inn_count; $j++) {
$val = hexdec($hex_splited[$i][$j]);
$arr_rgb[$i][$j] = $val;
foreach ($arr_rgb as $key => $value) {
$resultMax[$key] = max($value);
}
}
}
echo "<pre>";
var_dump($resultMax);
echo "</pre>";
echo "<table border='1'>";
for ($m=0; $m < $count2; $m++) {
echo "<tr>";
for ($k=0; $k < $inn_count; $k++) {
echo "<td>";
echo $arr_rgb[$m][$k];
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
Determining the maximum using max
only properly works for integers, so I would use array_map
with hexdec
to achieve that.使用
max
确定最大值仅适用于整数,因此我将使用array_map
和hexdec
来实现。
Then all it needs is a comparison of the value at position 1 with that maximum, and if they are the same, then the index gets added to the result array:然后它所需要的只是将 position 1 处的值与该最大值进行比较,如果它们相同,则将索引添加到结果数组中:
$result = [];
foreach($hex_splited as $key => $value) {
if(hexdec($value[1]) == max(array_map('hexdec', $value))) {
$result[] = $key;
}
}
var_dump($result);
This gets you 0, 1, 3
as result.结果是 0、1、3
0, 1, 3
(As IMHO it should be, according to your stated requirements - the value 00
at position 1 in the first sub-array is also the maximum of all values in that sub-array. If you need to exclude 0 values, then you'll have to modify accordingly.) (恕我直言,根据您声明的要求,第一个子数组中position 1 处的值
00
也是该子数组中所有值的最大值。如果您需要排除 0 值,那么您将必须相应修改。)
EDIT:编辑:
if all elements are equal, then return nothing
如果所有元素都相等,则不返回任何内容
Okay, that can also be implemented quite easily - we use array_count_values
, and if the count of that is only 1, then that means all the elements had the exact same value.好的,这也可以很容易地实现 - 我们使用
array_count_values
,如果它的计数只有1,那么这意味着所有元素都具有完全相同的值。
So then it becomes那么它变成了
foreach($hex_splited as $key => $value) {
if(count(array_count_values($value)) != 1 &&
hexdec($value[1]) == max(array_map('hexdec', $value))) {
$result[] = $key;
}
}
With that, you get [1, 3]
as $result here.有了这个,你得到
[1, 3]
作为 $result 这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.