php注意:数组到字符串的转换

时间:2018-12-07 05:22:42

标签: php arrays

我有以下数组$_SESSION['survey_ans'][]=$records; 并使用var_dump($_SESSION['survey_ans']);

获得结果
array(6) {
    [0]=> array(1) {
        [1]=> string(5) "vpoor" 
    } 
    [1]=> array(1) { 
        [10]=> string(4) "poor" 
    } 
    [2]=> array(1) { 
        [6]=> string(7) "average" 
    } 
    [3]=> array(1) { 
        [11]=> string(4) "good" 
    } 
    [4]=> array(1) { 
        [12]=> string(5) "vgood" 
    } 
    [5]=> array(1) { 
        [13]=> string(4) "good" 
    } 
}

但是当我运行这个

foreach($_SESSION['survey_ans'] as $key=>$value) {
    echo $key."-".$value."<br />";
}

我将收到错误消息“通知:数组中的字符串转换”。那么如何获得如下结果?

1, vpoor
10, poor
6, average
11, good
12, vgood
13, good

1 个答案:

答案 0 :(得分:2)

$_SESSION['survey_ans']的元素是数组,因此您需要遍历每个数组中的值以获得所需的输出。试试这个:

foreach($_SESSION['survey_ans'] as $result) {
    foreach ($result as $key => $value) {
        echo $key."-".$value."<br />";
    }
}

输出:

1-vpoor
10-poor
6-average
11-good
12-vgood
13-good

Demo on 3v4l.org