Faster or easier way to get data from a nested array - php

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().

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.

php foreach array inside array

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

Adding key in an Array PHP

Im studying in array, and I was wondering How can I add key to this kind of array?
{
"items":[
{
"count":"1",
"id":123,
"description":"Bag",
"price":11
},
{
"count":1,
"id":1234,
"description":"10% Discount",
"price":-1.1
}
],
"total":9.9,
"discount_total":9.9
}
because I needed convert the array to have a key base on the id inside the array.
{
"items":{
"123":{
"count":"1",
"cart_id":123,
"description":"Bag",
"price":11
},
"1234":{
"count":1,
"cart_id":1234,
"description":"10% Discount",
"price":-1.1
}
},
"total":9.9,
"discount_total":9.9
}
and this is my code
header('Content-Type: application/json');
$cart_array = json_decode('{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Bag"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}');
foreach ($cart_array->items as $item)
{
$construct["cart_id"] = $item->cart_id;
}
I wanted to ask how can I put the id in the array? I cant use $cart_array['id'] = $value, it returns error.
Uncaught Error: Cannot use object of type stdClass as array
I could really use some explanation here
Following code can help you.
<?php
$json = '{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Small Four Seasons"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}';
$data = json_decode($json,TRUE); //json decode
foreach ($data['items'] as $key => $value)
{
$data['items'][$value['cart_id']] = $value;
unset($data['items'][$key]);
}
echo "<pre>";print_r($data);die;
?>
You don't have to loop at all. You can use array_column to make an array associative with one line of code.
$cart_array['items'] = array_column($cart_array['items'], NULL, 'cart_id');
https://3v4l.org/cPD5n
You can use this code in your application to add keys to indexed array.
foreach($obj as $key=>$val){
foreach ($val as $index=>$content){
$data[$content['id']]=$content;
}
}
You can get same output json data as per you want :
$array = json_decode($data,true);
if(isset($array['items']) && count($array['items']) > 0){
foreach($array['items'] as $key => $value){
$value['cart_id'] = $value['id'];
unset($value['id']);
$array['items'][$value['cart_id']] = $value;
unset($array['items'][$key]);
}
}
echo "<pre>";print_r($array);
echo json_encode($array);

json decode - getting single array from object?

I have a json file which I decode using json_decode. The json file is an object which holds two arrays. I only want the first array but I'm having trouble figuring out how.
Json file
{
"app":{
"available":{
"stats":[
{
"name":"the name",
"at":"url"
},
{
"name":"the name",
"at":"url"
}
],
"stats2":[
{
"name":"the name",
"at":"url"
},
{
"name":"the name",
"at":"url"
}
]
}
}
}
I use
foreach($data3['app']['available'] as $name => $value)
{
foreach($value as $entry)
{
echo $entry['name'];
}
}
The output I get every name from both stats1 and stats2 arrays. I only want the names from stats1 array, not stats2. How can this be achieved?
because there are two arrays in app->available: stats and stats2
If you are interested in only stats, why don't you try:
foreach($data3['app']['available']['stats'] as $name => $value)
__UPDATE__
Try this one please
$in = '{"app":{"available":{"stats": [{"name":"the name","at":"url"},{"name":"the name", "at":"url"}],"stats2":[{"name":"the name","at":"url"},{"name":"the name","at":"url"}]}}}';
$obj = (array) json_decode($in, true);
foreach($obj['app']['available']['stats'] as $value)
{
foreach($value as $e => $v)
{
echo ($value['name'] );
echo ("\r");
}
}

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