【问题标题】:PHP filling the associative array with the right keyPHP用右键填充关联数组
【发布时间】:2017-06-06 12:25:55
【问题描述】:
 $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[$k]=$v; ?

标签: php arrays associative-array array-key


【解决方案1】:

你需要把$niz3[$niz[$k]]=$v;改成$niz3[$k]=$v;

$k 是“键”,通过将其传递给$niz,您正在访问已定义为$v 的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 2019-10-16
    • 1970-01-01
    • 2013-11-26
    • 2015-07-26
    • 1970-01-01
    • 2021-03-23
    相关资源
    最近更新 更多