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
Related
So i tried a lot of possible codes out but i can't seem to find a proper solution.
First let's start with the the wished array (i will show it in a json format as it's easier to read)
{
"transaction": {
"input": [
{
"address": "a",
"value": 4294967295
},
{
"address": "b",
"value": 51515
}
],
"output": [
{
"address": "aa",
"value": 551
},
{
"address": "bb",
"value": 66564
}
]
}
}
I'm using 2 foreach loops to get data that i wanna put in inputs & outputs
Here's the code im using:
//Get Output Addresses & Value
$tmp_array = array();
foreach($json['result']['vout'] as $a)
{
$value = $a['value'];
$address = $a['scriptPubKey']['addresses'][0];
$tmp_array = array('wallet' => $address, 'value' => $value);
$input = array_merge($input, $tmp_array);
};
$input = array('inputs' => $tmp_array);
$input = json_encode($input);
print_r($input);
That's the code for me getting the data and trying to put it into the array. Now i have a problem, it only adds data from the last iteration of the loop. I'm trying to get a code that gets it in a strucuture like above. Whatever solution gets sent, it should be applicable so i can paste the same code in the other loop that is for the outputs
You are assigning the $input variable after the loop with the value of $tmp_array which will be the value from the last iteration, as you described. To fix this you should initialize the $input array as empty array at the beginning and merge that with the new data:
//Get Output Addresses & Value
$inputs = array();
foreach($json['result']['vout'] as $a)
{
$value = $a['value'];
$address = $a['scriptPubKey']['addresses'][0];
$tmp_array = array('wallet' => $address, 'value' => $value);
$inputs[] = $tmp_array; // push to array
};
$input = json_encode(array('inputs' => $inputs));
print_r($input);
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.
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 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 />";
}
I'm looping through an array of $students and removing those that are already in the $enrolled array.
$i=0;
foreach($students as $student)
{
foreach($enrolled as $enrollment)
{
if ($enrollment->id == $student->id)
{
unset($students[$i]);
}
}
$i++;
}
return Response::json(array(
'available' => $students
));
That leaves me with the following output:
"available": {
"2": {
"id": "4"
"user_id": "4",
"teacher_id": null,
"parent_id": "4",
"active": "1"
}
}
What I'm trying to achieve is that available is an array, holding that one student. What am I doing wrong here?
Javascript arrays are zero-indexed so you cannot have an array with one element and an index that is not zero.
To get that from your php array, you need to re-index it before you encode it:
// re-index the array
$students = array_values($students);
return Response::json(array(
'available' => $students
));
See a simple example here.
for($i = 0; $i < count($students); $i++)
{
$student = $students[$i];
foreach($enrolled as $enrollment)
{
if ($enrollment->id == $student->id)
{
unset($students[$i]);
}
}
}
return Response::json(array(
'available' => array_values($students)
));
don't use foreach and unset on the same element, better would be for, because unset causes some problems to foreach if you think about it how foreach works (iterators, keys, whatever)