PHP用右键填充关联数组
PHP filling the associative array with the right key
$niz = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'watermelon',
'fruit5' => 'grapefruit'
);
$max = 'yellow';
$niz2 = array();
$niz3 = array();
foreach($niz as $k => $v){
if (strlen($v) <= strlen($max)) {
array_push($niz2, $v);
}
else {
$niz3[$niz[$k]]=$v;
}
}
print_r($niz3);
How can I get the appropriate key from the $niz array in my $niz3 associative array in the else statement?
即Array( [fruit4] => 西瓜
[fruit5] => 葡萄柚
)
我得到:
数组 ( [西瓜] => 西瓜
[葡萄柚] => 葡萄柚
)
您需要将 $niz3[$niz[$k]]=$v;
更改为 $niz3[$k]=$v;
,
$k
是 "key",通过将其传递到 $niz
您正在访问您已经定义为 $v
.
的值
$niz = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'watermelon',
'fruit5' => 'grapefruit'
);
$max = 'yellow';
$niz2 = array();
$niz3 = array();
foreach($niz as $k => $v){
if (strlen($v) <= strlen($max)) {
array_push($niz2, $v);
}
else {
$niz3[$niz[$k]]=$v;
}
}
print_r($niz3);
How can I get the appropriate key from the $niz array in my $niz3 associative array in the else statement?
即Array( [fruit4] => 西瓜 [fruit5] => 葡萄柚 )
我得到: 数组 ( [西瓜] => 西瓜 [葡萄柚] => 葡萄柚 )
您需要将 $niz3[$niz[$k]]=$v;
更改为 $niz3[$k]=$v;
,
$k
是 "key",通过将其传递到 $niz
您正在访问您已经定义为 $v
.