简体   繁体   中英

json_encode works for integers not for strings

I am trying to pass arrays from php to js and the json_encode function works on $MID (integer array) but fails to do anything on $name (array of strings).

Can anybody help me understand why it won't work?

$sql = "SELECT DISTINCT [materialID],[name],[categoryName],[materialResponsePerson] 
        FROM [SAP_Replication].[dbo].[IntranetProductResponsePerson]";

$params = array();
$stmt = sqlsrv_query( $conn, $sql, $params);

if( $stmt === false ) {
     die( print_r( sqlsrv_errors(), true));
}
$MID = array();
$name = array();
$cName = array();
$resPerson = array();

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
     array_push($MID,$row["materialID"]);
     array_push($name,$row["name"]);
     array_push($cName,$row["categoryName"]);
     array_push($resPerson,$row["materialResponsePerson"]);
}

echo json_encode($MID); //works and returns values
echo json_encode($name); //returns bool(false)

sqlsrv_close($conn);


Only echo one thing back to the Javascript! It is expecting to get one reply from your PHP code and not 4.

so I would do

echo json_encode([  'MID'       => $MID, 
                    'name'      => $name, 
                    'cName'     => $cName,
                    'resPerson' => $resPerson
                ]);

Then change your js code to read data from the right object

I have made a mistake when commenting the code. When I var_dump the $name variable it returns bool(false). Later I found out that meant that json_encode doesn't support string which have 'đ','ž','...' in them so I need to convert the array to utf-8. Thanks everyone for the help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM