php isset — 检测变量是否设置 foreach循环运用

时间:2022-03-22 23:11:41

例子

$a = 336 ;
$b = 33 ;
function large($x,$y){
if((!isset($x))||(!isset($y))){
// echo "this function require two numbers";
return false;
}
if($x>$y){
return $x;
}else{
return $y;
}
}
echo large($v,$b);

假设当前数组为
array(
0=>array('key1'=>'value1' , 'key2'=>'value2'),
1=>array('key1'=>'value1' , 'key2'=>'value3'),
2=>array('key1'=>'value2' , 'key2'=>'value4'),
...
999=>array('key1'=>'value2' , 'key2'=>'value5')
)
如何将这个array中 key1的value 相同的情况下 将key2的value合并成一个新的数组。求写一个方法将原数组转化问 如下数组
array(
0=>array('value1'=>array('value2','value3')),
1=>array('value2'=>array('value4','value5')),
...
)

题主,是无论 key1是否有重复都独立吗?下面是这样的做法

$arr = array(
0=>array('key1'=>'value1' , 'key2'=>'value2'),
1=>array('key1'=>'value1' , 'key2'=>'value3'),
2=>array('key1'=>'value2' , 'key2'=>'value4'),
999=>array('key1'=>'value2' , 'key2'=>'value5')
); $result = array();
foreach ($arr as $data) {
isset($result[$data['key1']]) || $result[$data['key1']] = array();
$result[$data['key1']][] = $data['key2'];
}
print_r($result); //输出如下
Array
(
[value1] => Array
(
[0] => value2
[1] => value3
) [value2] => Array
(
[0] => value4
[1] => value5
) )