I find it hard to explain but my page has a multidimensional array with all the users and I need to get values from the inner arrays without knowing the main key.
I'm not as experienced with arrays yet and I'm completely stuck right now. The function I use has 2 parameters. The first one is the input id of the user and the second is the array of the complete user list.
function userInfo($i, $users){
foreach($users['data'] as $user){
if($i = $user['id']){
return $user['SOMENAME?']['name'];
}
}
}
Here is a example of the array I'm working with:
{
"data": {
"Doe": {
"id": 266,
"title": "Doe title",
"name": "Doe",
"key": "Some key"
},
"John": {
"id": 412,
"title": "John title",
"name": "John",
"key": "Some key"
}
}
The function I have now simply returns Doe (The first value in the array) no matter how much arrays are in there.
How do I return the title or any of the other values when I don't know the name of the main key for that specific array?
There is an error in your if statement, where you are assigning a value, not ccomparing it (= vs == or ===).
For the purpose of your function, I don't think you need to know the key, because you're already in the array. eg.
function championInfo($i, $users){
foreach($users['data'] as $index => $user){
if($i == $user['id']){
return $user['name'];
}
}
}
foreach($users['data'] as $key => $user){
if($i = $user['id']){
return $champion[$key]['name'];
}
}
foreach($collecion as $key => $val){
That should get your results.
Try this;
foreach ($array as $key => $value) {
echo "ID: {$value['id']}, Title: {$value['title']}, Name: {$value['name']}, Key: {$value['key']}<br />";
}
another version (if you think this is more readable)
foreach ($array as $key => $value) {
list($id, $title, $name, $key) = array_values($value);
echo "ID: {$id}, Title: {$title}, Name: {$name}, Key: {$key}<br />";
}
Related
I am having trouble getting the name of a dynamic key from a JSON string.
I am using PHP
This is a sample of the JSON
{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}
I am using foreach to go trough the json key and get the values
foreach ($json as $obj) {
$search_term = $obj->_text;
$msg_id = $obj->msg_id;
}
But I am not sure how to get the value of the "dynamic_key" which changes every time, and because of that I also cannot get the values of "confidence and value" keys.
Any ideas on how to approach this?
Followed #Dimi, solution. This is what I ended up with
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "Entity: $key";
foreach ($data['entities'] as $keys){
$conf = $keys[0]['confidence'];
$answer = $keys[0]['value'];
echo "conf: $conf, answ: $answer";
}
}
Can you provide a couple more examples?
Or try this code and let us know if it breaks
<?php
$json='{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}';
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "VALUE IS $key\n values are ";
var_dump($val);
}
Using the data you've shown, there doesn't seem to be an array for the starting JSON.
But with that data the following will use foreach to both fetch the key and the data and then another sub-loop to fetch the confidencevalue...
$search_term = $json->_text;
$msg_id = $json->msg_id;
foreach ( $json->entities as $key => $entities ) {
echo $key.PHP_EOL;
foreach ( $entities as $entity) {
echo $entity->confidence.PHP_EOL;
}
}
If you decode the JSON as an array and if the dynamic key is the only key under entities, then:
$array = json_decode($json, true);
$dynamic = current($array['entities']);
$confidence = $dynamic['confidence'];
$value = $dynamic['value'];
Or shorter:
$confidence = current($array['entities'])['confidence'];
You can probably use reset, current and maybe array_pop etc.
I have a JSON that I would want to get the values from. However, the key values are typical key. They are not one worded.
[
{
"quality-of-service": "Good"
},
{
"quality-of-staff": "Great"
},
{
"quality-of-communication": "Excellent"
},
{
"value-for-money": "Excellent"
}
]
How do I get the values for the keys.
After decoding $array = json_decode($json, true), the first value would be $array[0]['quality-of-service'] which is not a good way to do it. You could loop:
foreach($array as $values) {
echo key($values) . " is " . current($values);
}
Or you can flatten the array:
$array = array_merge(...$array);
Then use $array['quality-of-service'] or loop it:
foreach($array as $key => $value) {
echo "$key is $value";
}
So I'm currently using XenForo to read values from an array inside an array, however when using this code I seem to get issues with the last foreach. ErrorException: Invalid argument supplied for foreach()
Array
{
"data": {
"type": "server",
"id": "121",
"attributes": {
"name": "1",
"ip": "127.0.0.1",
"port": 4000,
},
},
}
This is my foreach (which is getting the 'attributes' section of the above array).
foreach($json_array as $key => $arrays){
foreach($arrays as $array){
foreach($array as $key => $value){
$data[$key] = $value;
}
}
}
Does anyone know if there's a better way to just get the following values?
$value['name']
$value['ip']
$value['port']
If you want to loop:
foreach($json_array['data']['attributes'] as $key => $value){
print_r($value);
}
Try this way:
$data['name'] = $json_array['data']['attributes']['name'];
$data['ip'] = $json_array['data']['attributes']['ip'];
$data['port'] = $json_array['data']['attributes']['port'];
Quite simple. To get the attributes of the given array, you can try the code above.
No need to loop the array, just use $array[key] method to get the target value.
$data = $json_array['data']['attributes']
I have a json file with data like this (this is a partial view of the file to show structure):
{
"state": {
"ALABAMA": {
"ZOLD": [ "101", "102" ],
"ZNEW": [ "11", "12" ]
},
"ALASKA": {
"ZOLD": [ "5001", "5002", "5003", "5004", "5005", "5006", "5007", "5008", "5009", "5010"],
"ZNEW": [ "21", "22", "23", "24", "25", "26", "27", "28", "29", "20"]
}
}
}
What I want to do is search through it to find a value in the ZOLD field = $OLD, then return the value of the corresponding ZNEW array. I've tried going in with foreach and can get the arrays to echo out, but I'm not sure of what the value will be. Here's the code I have:
function translateZone($OLD)
{
$OLD = "5010"; //for testing purposes a constant but will be variable
$zStr = file_get_contents('getnew.json');
$zJson = json_decode($zStr,true);
foreach($zJson as $key=> $jsons)
{
foreach($jsons as $key=>$values)
{
foreach($values as $key=>$vals)
{
$counter=0;
foreach($vals as $key=>$vls)
{
$counter ++;
echo var_dump($vls);//I can see the values,but now what?
if ($vls == $OLD)
{
$zTemp = Help here -some array value of counter??
}
}
}
return $zTemp;
}
}
I've searched through a bunch of other questions but haven't found something close enough to help with the problem.
Additional information: I may or may not know the "state" string (i.e. "Alaska") but I may want to return this information as well based on the found value.
Thanks for the help.
Instead of trying to loop through ZOLD, you could use array_search (assuming that the $OLD value can only appear once in the data). This function will either return a number for the index of the value you search for or false if it cannot find it:
$index = array_search($OLD,$values['ZOLD']);
if ($index !== FALSE) {
$zTemp = $values['ZNEW'][$index];
}
This would replace your two innermost for loop (as you need the other loops to get down to this level) and iterate through each state. At this point as well, $key would be defined to your state name.
Here is another way to complete your task, this one with array_map function:
$jsonArray = json_decode($your_file_content, true);
$oldVal = "5005";
$result = [];
foreach( $jsonArray["state"] as $k => $v ) {
/**
* Here we're building an array or pairs ZOLD => ZNEW values
*/
$pairs = array_map(function($o, $n) {
return [ $o => $n ];
}, $v["ZOLD"], $v["ZNEW"]);
/**
* Filling up the result
*/
foreach( $pairs as $p )
if( isset($p[$oldVal]) )
$result[] = [
"state" => $k,
"ZNEW" => $p[$oldVal]
];
}
var_dump($result);
$result dump will contains a list or assoc arrays with "state" and "ZNEW" keys, if the corresponding ZNEW values will be found
I was trying to parsing json file below from a link but I still can't figure it out about parsing and display it with foreach.
data: [
{
id: "1072",
nik: "013977",
status: "",
name: "RAKHMAT KUSNADI",
birthdate: "1983-10-21",
email: "rakhmat.koes#gmail.com",
first_login: "0",
is_juri: "0",
what_juri: "",
categorized: "0",
back_stage: "0",
placement: [
{
rel_id: "1102",
employee_id: "1072",
department_id: "101",
dept: "Chip",
position_id: "1",
position: ""
}
],
profile_pics: "link"
},
{
id: "1069",
nik: "013377",
status: "",
name: "RENATA MARINGKA",
birthdate: "1987-05-20",
email: "",
first_login: "1",
is_juri: "0",
what_juri: "",
categorized: "0",
back_stage: "0",
placement: [
{
rel_id: "1099",
employee_id: "1069",
department_id: "101",
dept: "Chip",
position_id: "1",
position: ""
}
],
profile_pics: "link"
},
]
}
I want to display name and profile_pics where department id is 101.
Does anybody know how to parse it with foreach?
Reinventing the wheel, are we? Why not simply use:
$jsonObj = json_decode($jsonString);//returns stdClass instance, just an object
$jsonArr = json_decode($jsonString, true);//converts object to associative array
Read more on json_decode here... It's quite easy to use, really
If you decode the data to an array, you could loop through the data like so
while($item = array_shift($jsonArr))
{
foreach ($item as $key => $value)
{
echo $key.' => '.$value."\n";
}
}
Or simply use any old for/foreach loop on an object, its a traversable object anyway (though it doesn't implement the Traversable interface)
First step is to convert to an array
$data = json_decode($json);
Once you've got the array, you can then loop through it and check the values
$keepers = array();
foreach ($data as $item) {
if ($item->placement->department_id == 101) {
$keepers[] = $item;
}
}
Use json_decode
$arr = json_decode($jsonstring, true);
then use foreach loop
foreach($arr as $val) {
if($val['placement']['department_id'] == "101") {
//display what u want
}
}
Probably something like:
$data = json_decode($your_json);
foreach($data as $object) {
echo 'This is the name: ' . $object->name . PHP_EOL ;
}
$data = json_decode($json, true)
Then whatever info you want out you get out with the foreach loop
foreach ($data->id as $id)
{
echo $id;
}
With that you can set any variable like $data->nik as $nik or whatever you want then echo them back
usr this
foreach ($data->id as $id)
{
echo $id;
}