The [] operator is not supported for strings

I get an error for this code. This $sname[] = $rs['StudentId']; PHP string Fatal error: operator [] is not supported for strings $ 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++;  
    }                   
}
+3
source share
4 answers

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);

there was no “StudentId” in the user information array that you gave me, so I assume that you want to use the student array key if the “StudentId” line that I commented is actually used

+1
source

In the next cycle

foreach ($SchoolName as $sname) {

You assign a $SchoolNamevalue to each element $sname. Then on this line:

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

$sname . , .

+2

This should work - but you must have an index StudentIdpresent in the $ rs array, too ...

$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);

Live demo: http://codepad.org/HesEO4uF

0
source
$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;
                }               
            }
0
source

All Articles