Hi I have multidimensional array with db records where key is ID from database (first ID is id of workgroup, second ID is user id).
$users = array(
2 => array(
5 => array(
'firstname' => 'John'
'lastname' => 'Newman'
),
7 => array(
'firstname' => 'Peter'
'lastname' => 'Dow'
);
),
12 => array(
15 => array(
'firstname' => 'George'
'lastname' => 'Bush'
),
30 => array(
'firstname' => 'Ronald'
'lastname' => 'Reagan'
);
);
);
echo json_encode($users);
In javascript I would like access to array like users.workgroupId.userId.firstname. I know that javascript hasn ́t associative arrays, but I need use that kind of data from PHP. Is it possible in javascript?
3 Answers 3
Assuming that your code generates a valid JSON, here is a way to get the required details:
let workgroupId = 2; // Define your workgroup ID here
let userId = 5; // Define the user ID here
console.log(users[workgroupId][userId]. firstname); // prints `John` on the console
Comments
To be clear: Associative arrays become javascript objects when converted from php with json_encode and then unserialized in js. Your array in js will look like this:
var users = {
2: {
5: {
firstname: "John",
lastname: "Newman"
},
7: {
firstname: "Peter",
lastname: "Dow"
}
},
12: {
15: {
firstname: "George",
lastname: "Bush"
},
30: {
firstname: "Ronald",
lastname: "Reagan"
}
}
};
So just acces it like you would acces every other javascript object.
Example:
alert(users[2][5].lastname);
will output 'Newman'.
Comments
there is some syntax error in your php array. Right array is following.
$users = array(
2 => array(
5 => array(
'firstname' => 'John',
'lastname' => 'Newman'
),
7 => array(
'firstname' => 'Peter',
'lastname' => 'Dow'
)
),
12 => array(
15 => array(
'firstname' => 'George',
'lastname' => 'Bush'
),
30 => array(
'firstname' => 'Ronald',
'lastname' => 'Reagan'
)
)
);
echo json_encode($users);
Now following is the javascript code.
function myFunction(){
var users={"2":{"5":{"firstname":"John","lastname":"Newman"},"7":{"firstname":"Peter","lastname":"Dow"}},"12":{"15":{"firstname":"George","lastname":"Bush"},"30":{"firstname":"Ronald","lastname":"Reagan"}}};
alert(users[2][5].firstname);
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display an alert box.</p>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Comments
Explore related questions
See similar questions with these tags.
jsObject = { 2: { 5: { firstname : "John", lastname: "Newman" }} }. Usually a JSON converter likejson_encodeshould just do that for you!?