<?PHPHeader("Content-type:text/html;charset=utf-8");//character encoding Settings$servername= "localhost"; $username= "Root"; $password= "Root"; $dbname= "Tjks"; //Create a connection$con=Mysqli_connect($servername,$username,$password,$dbname); //Detecting Connections $sql= "SELECT * FROM Brands"; $result=Mysqli_query($con,$sql); if(!$result) { printf("Error:%s\n",Mysqli_error($con)); Exit();}$jarr=Array(); while($rows=Mysqli_fetch_array($result,Mysql_assoc)) { $count=Count($rows);//cannot be in a looping statement because the length of the row array is reduced each time you delete for($i= 0;$i<$count;$i++){ unset($rows[$i]);//Delete Redundant data } Array_push($jarr,$rows);}Print_r($jarr);//View ArraysEcho"<br/>"; Echo' ;Echo' Encoded JSON string: ';Echo $str=json_encode ($jarr);//encode the array in JSONEcho' <br> ';$arr=json_decode ($str);//the JSON decoding againEcho' Decoded array: ';Print_r($arr);//prints the decoded array, and the data is stored in an array of objectsMysqli_close($con);?>
The output reads as follows:
Array Array Array ([ID] + 3 [name] = + Tjks) Unicode encoded JSON data
As you can see, the direct Json_encode (), encoding, is to convert three arrays into JSON format, and the two sides will appear in brackets!! There's another way to do it.
<?PHPHeader("Content-type:text/html;charset=utf-8");//character encoding Settings$servername= "localhost"; $username= "Root"; $password= "Root"; $dbname= "Tjks"; //Create a connection$con=Mysqli_connect($servername,$username,$password,$dbname); //Detecting Connections $sql= "SELECT * FROM Brands"; $result=Mysqli_query($con,$sql); if(!$result) { printf("Error:%s\n",Mysqli_error($con)); Exit();}$jarr=Array(); while($rows=Mysqli_fetch_array($result,Mysql_assoc)) { $count=Count($rows);//cannot be in a looping statement because the length of the row array is reduced each time you delete for($i= 0;$i<$count;$i++){ unset($rows[$i]);//Delete Redundant data } Array_push($jarr,$rows);}Print_r($jarr);//View ArraysEcho"<br/>";Echo' ;$jobj=NewStdclass ();//Instantiate Stdclass, this is the PHP built-in empty class, can be used to pass the data, because the Json_encode after the data is in the form of an object array,//So we generate the time also to store data in the objectforeach($jarr as $key=$value){$jobj-$key=$value;}Echo' Object passed after the property: ';Print_r($jobj);//print the object after passing the propertyEcho' <br> ';Echo' Encoded JSON string: '. Json_encode ($jobj).‘ <br> ';//Print the encoded JSON stringMysqli_close($con);?>
The output reads as follows:
Array Array Array Array ([id] = 3 [name]+ =Objectarray Array ([ID] + 3 [name] + =) Tjks)) Encoded JSON string:{"0": {"id": "1", "name": "GNC"}, "1": {"id": "2", "Name": "TCBJ"}, "2": {"id": "3", "Name": "Tjks"}}
In this way, the brackets are gone, and the array becomes an ordered array!
Output database query results to JSON format in PHP