有人可以帮我找到每年的最低和最高关键字和价值吗? 我想要打印" tv-3"和" printer-1"。 这是php中的代码
$year = array (
"year 2015 " => array(
"Television" => "3",
"phone" => "4",
"personal computer"=> "5",
"printer" => "5",
),
"year 2016 " => array(
"Television" => "3",
"phone" => "7",
"personal computer"=> "4",
"printer" => "1",
)
);
答案 0 :(得分:0)
<?php
$year = array (
"year 2015 " => array(
"Television" => "3",
"phone" => "4",
"personal computer"=> "5",
"printer" => "5",
),
"year 2016 " => array(
"Television" => "3",
"phone" => "7",
"personal computer"=> "4",
"printer" => "1",
));
$result = [];
foreach($year as $val)
{
foreach($val as $k => $v)
{
$result[$k][] = $v;
}
}
array_walk($result, function(&$v){
$v = ['min' => min($v), 'max' => max($v) ];
});
var_dump($result);
输出:
kris-roofe@krisroofe-Rev-station:~$ php cal.php
array(4) {
["Television"]=>
array(2) {
["min"]=>
string(1) "3"
["max"]=>
string(1) "3"
}
["phone"]=>
array(2) {
["min"]=>
string(1) "4"
["max"]=>
string(1) "7"
}
["personal computer"]=>
array(2) {
["min"]=>
string(1) "4"
["max"]=>
string(1) "5"
}
["printer"]=>
array(2) {
["min"]=>
string(1) "1"
["max"]=>
string(1) "5"
}
}
答案 1 :(得分:0)
我认为这是您正在寻找的代码:
function find_min_max_products($year) {
foreach($year as $key => $value) {
$year_str = explode(' ', trim($key));
$year_str = end($year_str);
$products_with_min_qty = array_keys($value, min($value));
$products_with_min_qty = array_flip($products_with_min_qty);
$products_with_min_qty = array_fill_keys(array_keys($products_with_min_qty), min($value));
$products_with_max_qty = array_keys($value, max($value));
$products_with_max_qty = array_flip($products_with_max_qty);
$products_with_max_qty = array_fill_keys(array_keys($products_with_max_qty), min($value));
$products[$year_str] = array(
'min' => $products_with_min_qty,
'max' => $products_with_max_qty
);
}
return $products;
}
$year = array (
"year 2015 " => array(
"Television" => "3",
"phone" => "4",
"personal computer"=> "5",
"printer" => "5",
),
"year 2016 " => array(
"Television" => "3",
"phone" => "7",
"personal computer"=> "4",
"printer" => "1",
)
);
$products = find_min_max_products($year);
var_dump($products);
<强>输出强>
Array
(
[2015] => Array
(
[min] => Array
(
[Television] => 3
)
[max] => Array
(
[personal computer] => 3
[printer] => 3
)
)
[2016] => Array
(
[min] => Array
(
[printer] => 1
)
[max] => Array
(
[phone] => 1
)
)
)
希望它有所帮助!
答案 2 :(得分:0)
使用array_map
,array_intersect
,min
,max
和asort
函数的解决方案:
$result = array_map(function($y){
$slice = array_intersect($y, [min($y), max($y)]);
asort($slice);
return $slice;
}, $year);
// the min/max items are in ascending order (minimum values, then - maximun values)
print_r($result);
输出:
Array
(
[year 2015 ] => Array
(
[Television] => 3
[printer] => 5
[personal computer] => 5
)
[year 2016 ] => Array
(
[printer] => 1
[phone] => 7
)
)