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 )

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM