php foreach从数组中获取值

时间:2010-04-22 15:04:21

标签: php arrays loops foreach multidimensional-array

我无法访问数组中的值,数组看起来像这样,

Array
(
    [0] => Array
        (
            [id] => 1661
            [code] => 849651318
            [job_status] => 4
            [looking_for] => Lorem ipsum
            [keywords_education] => Derby University
            [sector_id_csv] => 10,21,9,22,26
            [last_job_title_1] => Programmer
            [last_job_employer_1] => HBOS
            [city] => Bury
            [expected_salary_level] => LEVEL_2
            [education_level] => COLLEGE
            [job_looking_for] => 
            [is_contract] => Y
            [is_permanent] => N
            [is_temporary] => Y
        )

)
Array
(
    [0] => Array
        (
            [id] => 402
            [code] => 849650059
            [job_status] => 3
            [looking_for] => Lorem ipsum
            [keywords_education] => Paris College
            [sector_id_csv] => 27,22,19,21,12
            [last_job_title_1] => Programmer
            [last_job_employer_1] => HSBC
            [city] => Bury
            [expected_salary_level] => LEVEL_2
            [education_level] => COLLEGE
            [job_looking_for] => 
            [is_contract] => N
            [is_permanent] => Y
            [is_temporary] => Y
        )

)
Array
(
    [0] => Array
        (
            [id] => 1653
            [code] => 849651310
            [job_status] => 3
            [looking_for] => Lorem ipsum
            [keywords_education] => Crewe University
            [sector_id_csv] => 27,15,19,21,24
            [last_job_title_1] => Programmer
            [last_job_employer_1] => ICI
            [city] => Bury
            [expected_salary_level] => LEVEL_2
            [education_level] => UNIVERSITY
            [job_looking_for] => 
            [is_contract] => N
            [is_permanent] => Y
            [is_temporary] => Y
        )

)

我正在努力获取价值,我已尝试执行以下操作,

foreach ($result as $rslt) {
    echo $rslt->id;
}

我也试过了,

foreach ($result as $rslt) {
    $rslt['id'];
}

但这一切都不起作用,我不知道为什么,任何人都可以帮忙吗?

3 个答案:

答案 0 :(得分:5)

在第一个例子中指出一些事情并希望澄清任何混淆:

foreach ($result as $rslt) {
    echo $rslt->id;
}

箭头操作符(->)被滥用。它通常用于在类对象上调用方法,在您的情况下$rslt将是一个类对象,而id将是一个方法,但事实并非如此。

在你的第二个例子中,

foreach ($result as $rslt) {
    $rslt['id'];
}

你差点撞到头上的钉子,但你忘了打电话给echoprint将值输出到屏幕上。

此外,您的$result数组在索引0处有一个子数组,因此需要更改

$rslt['id'];

以及echoprint声明。

echo $rslt[0]['id'];

答案 1 :(得分:1)

第二个是正确的,但您错过了echoprint

echo $rslt['id'];

从示例代码中,您不清楚$result是什么 如果$result包含所有列出的数组,则必须执行

foreach($result as $rslt) {
    echo $rslt[0]['id'];
}

进一步参考:

答案 2 :(得分:0)

我确信有人会在接下来的0.3秒内发布答案,所以我会尝试用你的方法来帮助你。显然你知道如何使用print_r(或var_dump)。您是否尝试在阵列中的$ rslt上使用它?你似乎很难理解$ rslt是什么。