John Davidson

php - how to select the content of each json array?

0 comments
Message:


I'm having trouble selecting only the values i need from json data :


foreach ($users as $row) {  
$usersDepartement = json_decode($row["departement"]);
var_dump($usersDepartement);
}

I get this


array(1) { [0]=> object(stdClass)#5 (1) { ["userDepartement"]=> string(0) "" } } array(4) { [0]=> object(stdClass)#6 (1) { ["userDepartement"]=> string(10) "33-gironde" } [1]=> object(stdClass)#7 (1) { ["userDepartement"]=> string(9) "40-landes" } [2]=> object(stdClass)#8 (1) { ["userDepartement"]=> string(17) "47-lot et garonne" } [3]=> object(stdClass)#9 (1) { ["userDepartement"]=> string(11) "64-pyrenees" } } array(3) { [0]=> object(stdClass)#5 (1) { ["userDepartement"]=> string(10) "33-gironde" } [1]=> object(stdClass)#10 (1) { ["userDepartement"]=> string(9) "40-landes" } [2]=> object(stdClass)#11 (1) { ["userDepartement"]=> string(17) "47-lot et garonne" } }

How in the world can i get all the values from one of the resulting arrays ?
I tried this : var_dump($usersDepartement[0});
But I get all the first values from each arrays not all the values from the first array :


object(stdClass)#5 (1) { ["userDepartement"]=> string(0) "" } object(stdClass)#6 (1) { ["userDepartement"]=> string(10) "33-gironde" } object(stdClass)#5 (1) { ["userDepartement"]=> string(10) "33-gironde" }


My Answer:
You can access the content of each JSON array by using the arrow operator (->) to access the specific key-value pairs within the JSON object. Here's an example of how you can select the content of each JSON array in a foreach loop:

php
foreach ($users as $row) {
$userData = json_decode($row, true); // Decode the JSON string into an associative array
$usersDepartement = $userData['department']; // Access the 'department' key from the JSON array

// Do something with the $usersDepartement value
echo $usersDepartement . "
";
}


In this example, we first decode the JSON string into an associative array using `json_decode($row, true)`. Then, we access the specific key-value pair we need from the JSON array using the key name (e.g., 'department'). You can replace 'department' with the key name you want to access from your JSON data.

Rate this post

4 of 5 based on 2526 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us