多维数组 - php 当我不使用冗余 if 语句时未定义的索引


multidimensional array - php Undefined index when I dont use a redundant if statement

我有一个多维数组,我想使用辅助函数访问该数组并将其中一个值从整数更改为字符串。下面的代码有效,但是如果我删除我并不真正需要的if语句,它会在帮助程序代码上给我一个未定义的索引错误

$stories = 此格式的多维数组

array(1) { 
    [0]=> array(4) 
        { 
            ["code"]=> string(1) "2" 
            ["user_name"]=> string(4) "Dave" 
            ["name"]=> string(11) "project one" 
            ["sample_id"]=> string(1) "2" 
        }
    }

访问我正在使用的阵列

foreach($stories as $key => $subarray) {
        if(array_key_exists('code', $subarray)){
            //if($stories[$key]['code'] > 0){        
                $stories[$key]['code'] = task_priority_text($stories[$key]['code']);
            //};
        }
}

以这种方式注释代码会引发错误,而取消注释会给出干净的结果。

这是我在其他地方使用过的辅助功能,效果很好

if ( ! function_exists('task_priority_text'))
{
    function task_priority_text($priority = FALSE)
    {
        $options = array('0' => 'Urgent', '1' => 'High', '2' => 'Medium', '3' => 'Low', '4' => 'Minimal');
    if($priority !== FALSE)
        return $options[$priority];
    else 
        return $options;
    }
}

我如何获得此 if 语句?


编辑

这是错误

A PHP Error was encountered
Severity: Notice
Message: Undefined index: Medium
Filename: helpers/tasks_helper.php
Line Number: 70

帮助程序的第 70 行是

return $options[$priority];

您正在多次循环数组中的每个项目。"外部"循环对数组中的每个项目运行一次,然后"内部"循环(其他人指出这是多余的)对$subarray变量中的每个项目再次运行。

foreach($stories as $key => $subarray) {
    foreach($subarray as $subkey => $subsubarray) {
        if(array_key_exists('code', $subarray)){
        //if($stories[$key]['code'] > 0){        
            $stories[$key]['code'] = task_priority_text($stories[$key]['code']);
        //};
        }
    }
}

这将是一个更好的方法:

foreach($stories as $story)
{
   $story['code'] = task_priority_text($story['code']);
}