Converting string object to array with php object to array conversion

If you’re working with JSON (JavaScript Object Notation) and either need to lớn convert a JSON string khổng lồ array or object & loop through it or vice-versa, take an array or object and convert it to a JSON string to lớn return, both can be done in PHPhường or JavaScript.quý khách hàng đang xem: How khổng lồ encode và decode json data in php

I broke up this post into three sections:

Convert JSON String khổng lồ PHPhường Array or Object

PHP.. >= 5.2.0 features a function, json_decode, that decodes a JSON string into a PHP.. variable. By default it returns an object. The second parameter accepts a boolean that when mix as true, tells it lớn return the objects as associative arrays. You can learn more about the json_decode function from PHP’s documentation.

Bạn đang xem: Converting string object to array with php object to array conversion

// JSON string $someJSON = ""; // Convert JSON string to lớn Array $someArray = json_decode($someJSON, true); print_r($someArray); // Dump all data of the Array echo $someArray; // Access Array data // Convert JSON string lớn Object $someObject = json_decode($someJSON); print_r($someObject); // Dump all data of the Object eđến $someObject->name; // Access Object data?>

Loop through PHPhường Array or Object

Loop through a PHPhường array or object with a foreach loop.

// Loop through Array $someArray = ...; // Replace ... with your PHPhường Array foreach ($someArray as $key => $value) emang lại $value . ", " . $value . ""; // Loop through Object $someObject = ...; // Replace ... with your PHP.. Object foreach($someObject as $key => $value) echo $value->name . ", " . $value->gender . ""; ?>lưu ý the differences in accessing the values of an array vs an object.

Convert PHP Array or Object to JSON String

PHP.. also features a json_encode function to lớn convert an array or object inlớn a string. Read more about the json_encode function from PHP’s documentation.

// Array $someArray = "Jonathan Suh", "gender" => "male" >, "William Philbin", "gender" => "male" >, "Allison McKinnery", "gender" => "female" > >; // Convert Array to lớn JSON String $someJSON = json_encode($someArray); emang lại $someJSON;?>lưu ý that I’m using the short array syntax that’s featured in PHPhường. 5.4+.

$array = array( "foo" => "bar", "bar" => "foo" ); // as of PHP. 5.4 $array = "bar", "bar" => "foo" >;?>

Convert JSON String to JavaScript Object

JavaScript has a built-in JSON.parse() method that parses a JSON string và returns an object.

script> // Convert JSON String to JavaScript Object var JSONString = ""; var JSONObject = JSON.parse(JSONString); console.log(JSONObject); // Dump all data of the Object in the console alert(JSONObject); // Access Object data/script>JSON.parse() is very well-supported, but there are browsers that bởi vì not support it (i.e. caniuse.com).

jQuery 1.x has a $.parseJSON() method that should fill in the gaps for those browsers if you’re needing to support them. You can also use the JSON-js library as a polyfill.

Xem thêm: Txgamedownload Là Gì Tới Máy Tính Không? Gameloop Pc: Tải Tencent Gaming 3

script> // Convert JSON String lớn JavaScript Object with jQuery var JSONString = "..."; // Replace ... with your JSON String var JSONObject = $.parseJSON(JSONString); console.log(JSONObject); // Dump all data of the Object in the console alert(JSONObject); // Access Object data/script>

Loop through JavaScript Object

script> // Loop through Object var JSONObject = ...; // Replace ... with your JavaScript Object for (var key in JSONObject) if (JSONObject.hasOwnProperty(key)) console.log(JSONObject + ", " + JSONObject); /script>

Convert JavaScript Object to lớn JSON String

JavaScript has a JSON.stringify method to convert a value into a JSON string.

script> var JSONObject = ; var JSONString = JSON.stringify(JSONObject); alert(JSONString);/script>Like JSON.parse, JSON.stringify is not supported in dinosaur browsers like JSON-js library lớn polyfill JSON.stringify as well.

You can combine the methods above sầu lớn create powerful, dynamic implementations on your trang web or application.

Let’s say you want to lớn get information from a database, safely return the data as JSON, and loop through it dynamically, you can bởi so with a bit of PHP.. & JavaScript with Ajax.

Dynamically Get JSON via Ajax and Loop Through JSON

Let’s assume your database structure looks like the following:

Table: people┌────┬────────────────────┬─────────┐| id | name | gender |├────┼────────────────────┼─────────┤| 0 | Jonathan Suh | male || 1 | William Philbin | male || 2 | Allison McKinnery | female || 3 | Becky Borgster | female || 4 | Victoria Einsteen | female |└────┴────────────────────┴─────────┘And you want lớn dynamically get a danh sách of people from the database based on gender, lượt thích this:


*

Let’s start with the front-kết thúc tệp tin index.html that’ll have sầu a select dropdown with genders khổng lồ select from, a table lớn display the results, và the script to lớn handle the Ajax. The JavaScript is written in jQuery.

id="gender" name="gender"> value="male">Male value="female">Female

id="people" border="1"> Name Gender
Now let’s create a response.php tệp tin to handle the back-kết thúc ngắn gọn xúc tích of getting the information from the database và returning the results as a JSON string.

// File: response.php // Get POST gender value $gender = $_POST; // Connect to lớn the database // replace the parameters with your proper credentials $connection = mysqli_connect("localhost", "username", "password", "database_name"); // Query to lớn run $query = mysqli_query($connection, "SELECT * FROM people WHERE gender = "" . $gender . """); // Create empty array lớn hold query results $someArray = ; // Loop through query và push results inlớn $someArray; while ($row = mysqli_fetch_assoc($query)) array_push($someArray, $row, "gender" => $row >); // Convert the Array lớn a JSON String and echo it $someJSON = json_encode($someArray); echo $someJSON;?>To get a more in-depth and better example of PHP-JSON-JavaScript/jQuery-Ajax interaction, read my jQuery Ajax call khổng lồ PHPhường Script with JSON Return post.

Xem thêm: Pure Fix Original Series - Anyone Running Tiny Chainrings And Cogs

Share ← Previous Post Next Post →

Related posts


*

Jonathan Suh

I’m a multidisciplinary developer & designer. I’m currently with the folks at Planning Center, và I’ve worked with well-known brands and agencies, which include Allstate, Brian Hoff Design, Leo Burnett, and OLSON. More about me. Follow darkedeneurope.com

Selected posts Post Topics Say hey! Subscribe

Stay up-to-date with all the blog posts via RSS or the Archives.


Chuyên mục: