Array to json format: convert array data to json format using PHP programming language. In PHP when you fetch data from database, data convert into json formate.
In this tutorial I will help you how to convert array to format json with simple steps. First you need to connect database in your page and select data from MySQL table. Selected data fetch into array format and store in a variable and you want to check, print it.
Now convert array data using json formatting code that I will give you in the below of the page.
Follow The Example:
<?php $con=mysqli_connect('localhost','root','','nes'); $qry=mysqli_query($con,"SELECT * from `contactus` ORDER BY `id` DESC"); $row=mysqli_fetch_array($qry); $arraydata = print_r($row, true); //Put data in new array $putarray = convert_to_array($arraydata); //Display Output $jsonendata=json_encode($putarray); echo $jsonendata."<br/>"; function convert_to_array($data) { if( substr($data, 0, 5) == 'Array' ) { $arraydata_contents = substr($data, 7, -2); $arraydata_contents = str_replace(array('[', ']', '=>'), array('@#', '^', ''), $arraydata_contents); $array_values = explode("@#", $arraydata_contents); for($i = 0; $i < count($array_values); $i++ ) { if( $i != 0 ) { $bits = explode('^', $array_values[$i]); if( $bits[0] != '' ) $array_output[$bits[0]] = $bits[1]; } } return $array_output; } } ?>
In PHP web application convert the request into an object using the PHP function to access the database and return the object as JSON using the json_encode() function.
Related posts