Get json object from it's position in the list - php

Let's say this is my json(I wont be able to change this json file):
{"success":true,
"users":{
"1036344647":{"name":"joel", "age":18},
"1036344365":{"name":"klant", "age":24},
"1036344352":{"name":"grabben", "age":23}
}
}
I also have a php code that collect this json data and decodes it.
$data = json_decode(file_get_contents("http://example.com/users/json"));
As you can see in my json each user has a random generated id that will change everytime i collect the data from my json file. Basicly i don't know any of the user ids.
But i still want to be able to print out a users name depending on it's position in the list.
For example: echo $data->users->[THE SECOND ID(the id with a user named "klant")]->name;
So i know this could be done easy if the json file was written as a array, but it is not.
Is there any way i can print out a object in the json depending on it's position in the list?

Try this:
function findUser($id)
{
$data = json_decode(file_get_contents("http://example.com/users/json"));
return isset($data[0]->users->$id) ? $data[0]->users->$id : null;
}
$user = findUser(1036344365);
var_dump($user);
It will output
object(stdClass)#4 (2) { ["name"]=> string(5) "klant" ["age"]=> int(24) }

You can build a 2nd array by "throwing away" those unique IDs with array_values() like so:
$array = json_decode($yourJSON, true);
$justValues = array_values( $array["users"] );
print_r( $justValues );
Output:
Array
(
[0] => Array
(
[name] => joel
[age] => 18
)
[1] => Array
(
[name] => klant
[age] => 24
)
[2] => Array
(
[name] => grabben
[age] => 23
)
)
You can then access each person's data like so:
echo $justValues[1]["name"]; // klant

No, it's not possible. JavaScript objects by design are unaware of "position" of their key-value pairs. Behind the scenes, that's what makes them powerful.
The first step is to rethink why you need to work with the JSON according to position.

Related

How to extract array from $_POST

I am receiving POST data from a form that is an array along with a few other fields. I need to take the array data only and pass it along in a post request of my own to a backend server as json.
The $_POST data looks like this:
Array (
[smsgte_submit] => Y
[alias] => Array (
[1] => Array (
[name] => mywife
[number] => 6135552001
[ssid] => 1 )
[2] => Array (
[name] => daughter
[number] => 6135553001
[ssid] => )
)
)
I only want to capture the alias entries and encode them in json.
I was successful in encoding the entire $_POST array into json with:
$data['jsonpost'] = json_encode($_POST);
which encoded the array as expected, however, I only want the alias array, so I tried the following:
$data['jsonpost'] = json_encode($_POST['alias']);
That, however doesn't work, it returns null to the server. Then I tried:
$data['jsonpost'] = json_encode(array_filter($_POST, 'alias'));
But that returned null.
Maybe I need to redesign my form, but in the end, I want a json array that looks like this:
{
"alias": {
"name":"mywife",
"number":"6135552001",
"ssid":"1"
},
"alias": {
"name":"daughter",
"number":"6135553001",
"ssid":"2"
}
}
It turns out that the following syntax should be correct:
$data['jsonpost'] = json_encode($_POST['alias']);
However, in order to get it to work, I had to split it as follows:
$jsonpost = json_encode($_POST['alias']);
$data['jsonpost'] = jsonpost;
I switched back and forth between the two options a few times, but only the second one works, at least with PHP 7.3.5.

Editing a poorly formatted JSON string in PHP

I have a site which I used JSON to save some data.
Here is how it saves data
{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}
Note: I know this is a poor way of doing it but I did it when I was not so vast!
The 1 is the user_id which changes according to the id of the user that takes an exam on the platform. The english, physics are the subjects this user took.
The maximum number of exam a user can take at a time is for so the json string will look like {"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"},"maths":{"grade":"7","time":"79"},"chemistry":{"grade":"3","time":"48"}}}
First I think this is the best way to save the result as a JSON string
[{"subject":"english","grade":"7","time":"79"}, {"subject":"physics", "grade":"3","time":"48"}}]
My problem is that I want to use PHP to work on the former on. I have done some few stripping of the string and I'm left with this {"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}
I tried this chunk
$JSONResult = json_decode($aScore->result);
foreach ($JSONResult as $subjectKey => $aSubject)
{
foreach ($aSubject as $theResult)
{
$userResult = '
Subject: **This is what I've not been able to get**
Grade: '.$theResult->grade.'
Time: '.$theResult->time.'
';
}
}
I tried $aSubject->subjectKey to get the associative key value from the first foreach statement but it did not work
Any help?
Added: Please leave comments about the way the JSON string was stored. I'd love to learn.
You don't need the inner loop. Each subject is just a single object, not an array. And the subject key is just $subjectKey, it's not a part of the object.
$JSONResult = json_decode($aScore->result, true); // to get an associative array rather than objects
foreach ($JSONResult as $subjectKey => $aSubject) {
$userResult = "
Subject: $subjectKey
Grade: {$aSubject['grade']}
Time: {$aSubject['time']}
";
}
DEMO
You could use the second argument to json_decode!
It changes your $JSONResult from stdClass to an associative Array!
Which means you can do something like this:
$str = '{"1":{"english":{"grade":"7","time":"79"},"physics":{"grade":"3","time":"48"}}}';
$result = json_decode($str, true); // Put "true" in here!
echo "<pre>".print_r($result, true)."</pre>"; // Just for debugging!
Which would output this:
Array
(
[1] => Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
)
And in order to loop through it:
foreach ($result as $idx => $exams) {
echo $exams['english']['grade']."<br>";
echo $exams['physics']['grade']."<br>";
}
Which would output this:
7
3
Update
Without knowing the containing arrays data (Based on the example above)
$exams will be an Array (which could contain any sort of information):
Array
(
[english] => Array
(
[grade] => 7
[time] => 79
)
[physics] => Array
(
[grade] => 3
[time] => 48
)
)
If you want to loop through $exams:
foreach ($result as $idx => $exams) {
foreach ($exams as $subject => $info) {
echo $info['grade']."<br>";
}
}
This would produce the same output as the above example, without needing to know a subject name!

how to get value from array with 2 keys

i have array like
Array
(
[1] => Array
(
[user_info] => Array
(
[id] => 1
[name] => Josh
[email] => u0001#josh.com
[watched_auctions] => 150022 150031
)
[auctions] => Array
(
[150022] => Array
(
[id] => 150022
[title] => Title of auction
[end_date] => 2013-08-28 17:50:00
[price] => 10
)
[150031] => Array
(
[id] => 150031
[title] => Title of auction №
[end_date] => 2013-08-28 16:08:03
[price] => 10
)
)
)
so i need put in <td> info from [auctions] => Array where is id,title,end_date but when i do like $Info['id'] going and put id from [user_info] when i try $Info[auctions]['id'] there is return null how to go and get [auctions] info ?
Try:
foreach( $info['auctions'] as $key=>$each ){
echo ( $each['id'] );
}
Or,
foreach( $info as $key=>$each ){
foreach( $each['auctions'] as $subKey=>$subEach ){
echo ( $subEach['id'] );
}
}
Given the data structure from your question, the correct way would be for example:
$Info[1]['auctions'][150031]['id']
$array =array();
foreach($mainArray as $innerArray){
$array[] = $innerArray['auctions'];
}
foreach($array as $key=>$val){
foreach($val as $k=>$dataVal){
# Here you will get Value of particular key
echo $dataVal[$k]['id'];
}
}
Try this code
Your question is a bit malformed. I don't know if this is due to a lacking understanding of the array structure or just that you had a hard time to explain. But basically an array in PHP never has two keys. I will try to shed some more light on the topic on a basic level and hope it helps you.
Anyway, what you have is an array of arrays. And there is no difference in how you access the contents of you array containing the arrays than accessing values in an array containing integers. The only difference is that what you get if you retrieve a value from your array, is another array. That array can you then in turn access values from just like a normal array to.
You can do all of this in "one" line if you'd like. For example
echo $array[1]["user_info"]["name"]
which would print Josh
But what actually happens is no magic.
You retrieve the element at index 1 from your array. This happens to be an array so you retrieve the element at index *user_info* from that. What you get back is also an array so you retrieve the element at index name.
So this is the same as doing
$arrayElement = $array[1];
$userInfo = $arrayElement["user_info"];
$name = $userInfo["name"];
Although this is "easier" to read and debug, the amount of code it produces sometimes makes people write the more compact version.
Since you get an array back you can also do things like iterating you array with a foreach loop and within that loop iterate each array you get from each index within the first array. This can be a quick way to iterate over multidimensional array and printing or doing some action on each element in the entire structure.

PHP - search for a key value and then find the value of another key in the same object subarray

I've searched a lot for this, and found several similar questions, but none quite address what I'm trying to accomplish.
I'm trying to write a code that will search a PHP (multi)multidimensional array to see which subarray contains the unique key value that I have. Then I would like it to return the value of a different key in that same object subarray.
$Arraytosearch = Array(
.
//various other subarrays
.
[fields] => Array (
.
.
.
//I don't know the number of the object subarray
[x] => PodioTextItemField Object (
[__attributes] => Array (
[field_id] => 37325091
[type] => text
[external_id] => id
[label] => ID
[values] => Array (
[0] => Array (
[value] => REF100019 ) )
[config] => Array (
[description] => [settings] => Array (
[size] => small )
[required] => [mapping] => [label] => ID [visible] => 1 [delta] => 2 ) )
.
.
.
//(and so on)
I'd like to write a function that will return "REF100019" by supplying the value of the field_id => 37325091.
Some things I have tried that I couldn't get to work:
foreach
and new RecursiveIterator although the tutorials I read weren't useful for my case here.
Even though the array looks complicated, I think it will be easy since I already have the field id of the parent array.
Thank you in advance for any guidance or sample codes that will work!
Background: This is a part of the response I get from Podio after submitting a request to their API. I just don't know how to take that response and get the piece I need (the ID) so that I can echo it for users).
EDIT: Thank you Orangepill and Barmar for the support. I tried your code. But was getting an error, which made me realize I hadn't given you the full array. I figured out how to get the Podio response to display in a more readable format (I was reading the full JSON response before from the Podio debug file which was super confusing), and figured out the full array is actually structured as I have shown below.
I then took your code and was able to figure out how to make it work for my scenario (see below). Very proud of myself considering I have never written any code before, but I couldn't have done it without your help! Thanks again!
$Arraytosearch = Array(
[items] => Array(
[0] => PodioItem Object(
[_attributes] => Array(
[fields] => Array (
[x] => PodioTextItemField Object (
[__attributes] => Array(
[field_id] => 37325091
[values] => Array(
[0] => Array(
[value] => REF100019 ) )
Note: For anyone who is new to programming like myself and wants the Podio response (or any JSON string) to display in a "pretty" readable format like above, use the code (from Display an array in a readable/hierarchical format thanks to Phenex):
print "<pre>";
print_r($Arraytoformat);
print "</pre>";
And finally, the full code I used (using Orangepill's answer below) which searches the objects and arrays and gives me what I have been searching for for days now is as follows:
$Arraytosearch = PodioItem::filter(APP_ID, $filterParams);
$fieldID = 37325091;
function getFirstValueByFieldId($fieldId, $Arraytosearch){
foreach($Arraytosearch["items"][0]->__attributes["fields"] as $textitem){
if ($textitem->__attributes["field_id"] == $fieldId){
return $textitem->__attributes["values"][0]["value"];
}}}
$refID = getFirstValueByFieldId($fieldID, $Arraytosearch);
The podio-php library has built-in methods that handle all this for you. There's no need to mess with the __attributes property yourself.
You can see a bunch of examples at https://github.com/podio/podio-php/blob/master/examples/items.php
In your case:
// Get item collection
$itemCollection = PodioItem::filter(APP_ID, $filterParams);
$fieldID = 37325091;
foreach ($itemCollection['items'] as $item) {
// Get the field from the item
$field = $item->field($fieldID);
// Now you can print the value of that field
print $field->humanized_value;
// Or if you don't want to have the content sanitized:
print $field->values[0]['value'];
}
There is a lot of ways to skin this cat... this is probably the most straight forward
function getFirstValueByFieldId($fieldId, $Arraytosearch){
foreach($Arraytosearch["fields"] as $textitem){
if ($textitem->__attributes["field_id"] == $fieldId){
return $textitems->__attributes["values"][0]["value"];
}
}
}
to Use in your case would be
echo getFirstValueByFieldId("37325091", $Arraytosearch);
Basically it walks the elements in the fields array and returns the value in the first associated value in the values array where field_id is equal to the parameter of the function.

Passing a Python list to php

I'm very new to php and I've been spending quite some type understanding how to pass arguments from Python to php and conversely.
I now know how to pass single variables, but I am still stuck and can't seem to find an answer to this one:
Php calls a Python script (that part works) that returns a list of strings. I'd like to process this list in php.
When I try:
print mylist
in myscript.py, and then :
$result = exec('python myscript.py')
it looks like php understands $result as a single string (which I agree makes sense).
I understand that maybe json can help or that I somehow need to use a dictionary instead of a list in python. However I can't figure out how exactly.
If anyone can help, it will be much appreciated! Thanks!
For instance:
myscript.py
import json
D = {'foo':1, 'baz': 2}
print json.dumps(D)
myscript.php
<?php
$result = json_decode(exec('python myscript.py'), true);
echo $result['foo'];
You're using stdin / stdout to transfer the data between the programs, that means you'll have to encode your structure somehow in order to let your receiving program parse the elements.
The simplest thing would be to have python output something like a comma separated list
Adam,Barry,Cain
and use
$result = explode(exec('python myscript.py'));
on the php side to turn your string data back into an array.
If the data is unpredictable (might contain commas) or more structured (more than just a simple list) then you should go for something like json as suggested by Krab.
Apparently your question was misleading. Was redirected here thinking this a solution for converting python lists to php array.
Posting a naive solution for ones wanting to convert lists to php array.
// Sample python list
$data = '[["1","2","3","4"],["11","12","13","14"],["21","22","23","24"]]';
// Removing the outer list brackets
$data = substr($data,1,-1);
$myArr = array();
// Will get a 3 dimensional array, one dimension for each list
$myArr =explode('],', $data);
// Removing last list bracket for the last dimension
if(count($myArr)>1)
$myArr[count($myArr)-1] = substr($myArr[count($myArr)-1],0,-1);
// Removing first last bracket for each dimenion and breaking it down further
foreach ($myArr as $key => $value) {
$value = substr($value,1);
$myArr[$key] = array();
$myArr[$key] = explode(',',$value);
}
//Output
Array
(
[0] => Array
(
[0] => "1"
[1] => "2"
[2] => "3"
[3] => "4"
)
[1] => Array
(
[0] => "11"
[1] => "12"
[2] => "13"
[3] => "14"
)
[2] => Array
(
[0] => "21"
[1] => "22"
[2] => "23"
[3] => "24"
)
)
$str = "[u'element1', u'element2', 'element3']";
$str = str_replace( array("u'", "[", "]"), array("'", ""), $str );
$strToPHPArray = str_getcsv($str, ",", "'");
print_r( $strToPHPArray );
Outputs
Array
(
[0] => element1
[1] => element2
[2] => element3
)

Categories