php foreach array inside array - php

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']

Related

JSON Get the name of dynamically changing key with PHP

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.

Faster or easier way to get data from a nested array

I'm trying to get data from an associated array inside an associated array. The data is like this:
{
"keys": [
{
"kid": "28f5813e327ad14caaf1bf2a12368587e882b604",
"e": "AQAB",
"kty": "RSA",
"alg": "RS256",
"n": "y-Ssr1zlqWaldUHklobfrJLZkkBYrLVKTOk9SnzkG3v2LPB-0lxLQjm8UDpdZRErn4_FfCQ6b7SAObUp2XgcD-fwmYfq34mvY-xGcvlEarcOFdVD9cwkGBdXL_VJYzqLtvuAL30mbD2TGhIp-QCV-rqb6ujh75vSmwWH1Kkx1HNkVbXHHETvX7h8kj3zmCtRdMGeQJ2YrcJHz3GnJx0M2Zpq1HiAXkYL9GUYsq9maONfsrSeACu7T0W4v-XTppsV3DwU89D_eFd8gJsONvFZPvbqyGivdXYTnYNo7Jf01IisO4JZZrNgUlVT-gPkTM1O1UXevgFY62Br8mBot6Lw6Q",
"use": "sig"
},
{
"alg": "RS256",
"n": "timkjBhJ0F7fgr5-ySitSoSNmUqYcVKgWaUd52HUYPowNwdw1vOWYHuSVol47ssOOaF7dRjgoVHyo_qNgy7rdlU0pUidiYTB6lwSAQYyvk6WAipkpzWH8cr875BMUREyN5aEy-iKsYTB3HeT-gEnLI697eETZtSB8rwlDvyRy7l0wD1GVj4SKTd4P2a2qNCgCfkZzzKqPgmIrPtwkEZb43Cz-A7AfwyXxrMljTkghKkp4zkFRtXplIGjC5LcPZRLSseTYwHP2pV4AtE5KzYxDmtDmY6RyZaMZc_WXNvKBFcO3Rypo4F63lE2x5f7EIbpATWydXq3CMLitLsPor22ow",
"use": "sig",
"kid": "2c3fac16b73fc848d426d5a225ac82bc1c02aefd",
"e": "AQAB",
"kty": "RSA"
}
]
}
To get the kid, for example, is I have to do two foreach() before I can get the data:
foreach ($certs as $key => $val) {
foreach($val AS $key2 => $val2){
$kid = $val2->kid;
}
}
Is there a faster or a more standard way to get that data?
You can use array_column to get the kid from the array. First, you need to decode the JSON into an array and then use it as
$arr = json_decode($json, true);
print_r(array_column($arr['keys'],'kid'));
Live Demo
try this code,
$json = json_decode($certs);
foreach ($json->keys as $key => $value) {
$kid= $value->kid;
}
easy way to get kid value, using only one foreach().

How to add data in JSON using PHP

I have a json file with the following syntax:
[
{
"fields": {
"service_number": "service_number",
"physical_address": "physical_address",
"account_id": "account_id",
"contact_id": "contact_id"
},
"someId": "asd23f",
"status": "Active",
"perCode": "1",
"idCode": "0987",
"nextCode": "09"
},
{
"fields": {
"service_number": "service_number",
"physical_address": "physical_address",
"account_id": "account_id",
"contact_id": "contact_id"
},
"someId": "789096",
"status": "Active",
"perCode": "1",
"idCode": "076543",
"nextCode": "09"
}
]
I would like to use a for loop in order to add something like a userID before or after the nextCode. Is there any solution to this?
So far, I tried this:
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
foreach ($val as $key=>$c)
{
if (is_array($c))
continue;
$data .= $data . "user_id:$userId";
}
}
Of course it does not make the trick, any ideas please?
There are a few problems.
First, the foreach loop works with a copy of the array it's iterating, so modifying one of the items there won't change the original array.
Then, your inner foreach loop is overwriting the $key from the outer loop. That would cause problems, but it's okay, because you don't actually need the inner loop.
Finally, after you've decoded the JSON string, $data will be an array, so appending to it with .= won't work, and even if it did, you'd just be sticking something on the end of it rather than at the specific point where your loop is.
Just refer to the specific key you need and set the value there.
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
$data[$key]['user_id'] = $userId;
}
$data = json_encode($data);
Another way which is slightly shorter is pass the value by reference &:
$data = json_decode($file, true);
foreach ($data as &$val) {
$val['user_id'] = $userId;
}
https://3v4l.org/ZF4Ve
This is how you can add an element to a parsed JSON and recostruct it back into a JSON:
// parse the JSON into an array
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
// add the userID to each element of the main array
// it will be inserted after the last element (after nextCode)
$data[$key]['userID'] = 'some-id';
}
// if needed, parse the array back to JSON
$data = json_encode($data);
I explain to you
The following expression converts the information from string to array
$data = json_decode ($file, true);
So in your foreach you only have to add the key
$data = json_decode($file, true);
foreach ($data as $key => $val)
{
foreach ($val as $k=>$c)
{
if (is_array($c))
continue;
$data[$k]['user_id'] = $userId;
}
}
I see everybody answered for array options. I don't see why not using object, though.
I would do it like this:
$data = json_decode($file);
foreach ($data as &$field)
{
$field->userID = $userId;
}
$data = json_encode($data);

For each get a value with a variable key

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 />";
}

PHP json string: getting an associative array object

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

Categories