在Array中查找键并显示值

时间:2011-05-02 09:43:02

标签: php arrays codeigniter

我对数组有点问题。我使用codeigniter。我想做的是这样的事情:

$studentSchool = $students->schoolId;
echo $shools->id[$studentSchool]->schoolName;

它在foreach $ students循环中,与学校的数组看起来像这样:

Array ( [0] => stdClass Object ( [id] => 1 [schoolName] => Akademia Ekonomiczna ) [1] => stdClass Object ( [id] => 2 [schoolName] => Politechnika ) )

这是我在php和codeigniter中的第一步,所以请怜悯:)

2 个答案:

答案 0 :(得分:2)

如果$schools是数组,则必须将其作为数组访问。它没有id属性;

您应该构建$schools数组,使元素索引对应于学校的ID。即你应该:

Array ( 
    [1] => stdClass Object ( [id] => 1 [schoolName] => ... ) 
    [2] => stdClass Object ( [id] => 2 [schoolName] => ... ) 
)

然后你可以这样做:

echo $schools[$studentSchool]->schoolName;

或者,如果学校按ID排序且ID是连续的,您也可以这样做:

 echo $schools[$studentSchool - 1]->schoolName;

否则你必须循环遍历数组以找到给定ID的正确条目,这是昂贵且不必要的。

Learn more about arrays.

答案 1 :(得分:1)

这是你要找的吗?

foreach ($students as $student):

    // Prints the School name for this student
    echo $student->schoolName;

endforeach;

或许这个?:

// Prints the School name for the first student
echo $students[0]->schoolName
编辑:这是你想要的吗?

$studentSchool = $students->schoolId;
echo $shools[$studentSchool]->schoolName;