字符串不支持[]运算符

时间:2011-05-05 11:02:50

标签: php arrays foreach

对于这段代码我得到了错误。这一行$sname[] = $rs['StudentId']; PHP致命错误:字符串不支持[]运算符     $ sname = array();     $ I = 0;

foreach($data as $rs){

    foreach($SchoolName as $sname){
//      echo $rs['SchoolName'].'=='.$sname."<br />";
        echo $i."<br />";                  
        if($rs['SchoolName'] == $sname){
            $sname[] = $rs['StudentId'];
        }   
        $i++;  
    }                   
}

4 个答案:

答案 0 :(得分:2)

在以下循环中,

foreach ($SchoolName as $sname) {

您要将$SchoolName的每个元素分配给$sname。然后在这一行:

$sname[] = $rs['StudentId'];

您尝试将$sname视为数组。我怀疑你有一个重复的变量名。

答案 1 :(得分:1)

WORKING DEMO

$SchoolNames = Array(10003, "Southwestern College", "National University", "Western Governors University", "Southwestern College Admissions Center - Evaluations Dept");
$data = array(
    0 =>  Array(
        'STU_MANG_fname' => "Jennifer",
        'STU_MANG_lname' => "patel",
        'SchoolName' => "Southwestern College Admissions Center - Evaluations Dept",
        'ShipAddress1' => "900 Otay Lakes Road",
        'ShipState' => "CALIFORNIA" 
    )
);


foreach($data as $studen_info){
    foreach($SchoolNames as $id=>$school_name){
        if($studen_info['SchoolName'] == $school_name){
            $student_names[$school_name] = $id;
            //$student_names[$school_name] = $student_info['StudentId'];;
        }
    }
}

print_r($student_names);

你给我的学生信息数组中没有'StudentId'所以我假设你想要使用学生数组的密钥,如果实际上有一个'StudentId'使用行我注释掉了

答案 2 :(得分:0)

这应该有效 - 但你必须在$ rs数组中有StudentId索引......

$data = array(
    array("SchoolName" => "Roy", "StudentId" => "1000,1001,1002"),
    array("SchoolName" => "MIT", "StudentId" => "2000,2001,2002"),
    array("SchoolName" => "Southwestern College", "StudentId" => "3000,3001,3002"),
    array("SchoolName" => "National University", "StudentId" => "4000,4001,4002"),
    array("SchoolName" => "Western Governors University", "StudentId" => "5000,5001,5002"),
);

$return = array();

foreach($data as $rs){
    $return[$rs['SchoolName']] = $rs['StudentId'];
}

print_r($return);

现场演示:http://codepad.org/HesEO4uF

答案 3 :(得分:0)

$sname = array();
            $k=0;
            for($i=0;$i<count($data);$i++)
            {   
                $id_str ='';            
                for($j=0;$j<count($SchoolName);$j++)
                {                   
                    if($data[$i]['SchoolName'] == $SchoolName[$j]){
                        $id_str .= intval($data[$i]['StudentId']).",";
                    }
                    $sname[$SchoolName[$j]] = $id_str;
                }               
            }