duanbin198788
2017-01-21 16:43
浏览 42
已采纳

PHP用正确的密钥填充关联数组

 $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? 

I.e. Array( [fruit4] => watermelon [fruit5] => grapefruit )

I get: Array ( [watermelon] => watermelon [grapefruit] => grapefruit )

图片转代码服务由CSDN问答提供 功能建议

  $ niz = array(
'fruit1'=&gt;'apple',
'wruit2  '=&gt;'orange',
'fruit3'=&gt;'grape',
'fruit4'=&gt;'西瓜',
'fruit5'=&gt;'葡萄柚'
); 
 \  n $ max ='yellow'; 
 $ niz2 = array(); 
 $ niz3 = array(); 
 
 foreach($ niz as $ k =&gt; $ v){
 
 if(  strlen($ v)&lt; = strlen($ max)){
 array_push($ niz2,$ v);  
} 
其他{
 $ niz3 [$ niz [$ k]] = $ v; 
} 
} 
 print_r($ niz3); 
 
如何从$获取相应的密钥? 在else语句中我的$ niz3关联数组中的niz数组?  
   
 
 

即。 数组([fruit4] =&gt;西瓜 [fruit5] =&gt;葡萄柚 )

我得到: Array([西瓜] =&gt;西瓜 [葡萄柚] =&gt;葡萄柚 )

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • donglan8870 2017-01-21 16:45
    已采纳

    You need to change $niz3[$niz[$k]]=$v; to $niz3[$k]=$v;,

    $k is the "key", by passiing it into $niz you are accessing the value, which you have already defined as $v.

    点赞 打赏 评论

相关推荐 更多相似问题