Access values in nested foreach PHP - php

I have a JSON file. (Steam API). I want to display player inventory in my website. I use this url: https://steamcommunity.com/id/majidsajadi/inventory/json/730/2
Then I decode it with json_decode function.
Now there are two arrays: rgInventory and rgDescription. I need to check if class id in rgInventory and classid in rgDescription match I use some of values in igDescription.
So I think I should use 2 foreach loop and a if condition to check if class id match. then I echo out the information I need.
The question is how should I use nested foreach?

You can use two nested foreach loops like this:
Assuming that $decoded_data is your decoded data after applying json_decode() function on the end result, like this: $decoded_data = json_decode($your_json_data, true);
foreach($decoded_data['rgInventory'] as $arr1){
foreach($decoded_data['rgDescriptions'] as $arr2){
if($arr1['classid'] == $arr2['classid']){
// both the classid matches
// your code
}
}
}

Try this code:
$steamData = json_decode(file_get_contents("https://steamcommunity.com/id/majidsajadi/inventory/json/730/2"), true);
if($steamData["success"] != 1){
exit();
}
$match = array();
foreach($steamData["rgInventory"] as $v1){
$match[$v1["classid"]]["match"] = false;
$match[$v1["classid"]]["count"] = 0;
}
foreach($steamData["rgDescriptions"] as $v2){
if(array_key_exists($v2["classid"],$match)){
$match[$v2["classid"]]["match"] = true;
$match[$v2["classid"]]["count"]++;
}
}
print_r($match);

Related

Merging two queries to one JSON object

I have two queries:
1) $result = $this->_db->get_where("wishes",array("is_open"=>1))->result_array();
2) $requirements_result = $this->_db->get("requirements")->result_array();
I'm trying to output the data in this JSON format:
{
[
{
id:12,
title:"Meet Messi",
image_url:"http://dsadsa.dsadsa",
previewImageUrl:"http://kdjfla.com"
is_open:"true"
requirements: [
{
id: 123,
title:"kiss Messi",
is_complete: true
}
]
}
]
}
}
I created two models (one for each query).
This is what I've done so far:
$result = $this->_db->get_where("wishes",array("is_open"=>1))->result_array();
$requirements_result = $this->_db->get("requirements")->result_array();
$return_array = array();
foreach ($result as $value)
{
$wishes_model = new wishes_model();
$wishes_model->init_wishes($value);
$return_array[] = $wishes_model;
}
return $return_array;
How to i insert the requirements result to create this JSON?
First, create your wishes array as an associative array, with the ID as the key:
$wishes_array = array();
foreach ($results as $value) {
$wishes_model = new wishes_model();
$wishes_model->init_wishes($value);
$wishes_array[$value['id']] = $wishes_model;
}
Then you can add the requirements to the appropriate wish:
foreach ($requirements_results as $req) {
$wishes_array[$req['wish_id']]->requirements[] = $req;
}
I'm making some assumptions about which things in your application are associative arrays versus objects. You should be able to adjust this to match your specific implementation.
I have couple of question but for now i am gonna guess.
You can try array_merge but it will overwrite same keys.
If you don't want that you can add prefix to keys and then merge both array.
And i think rest of the solutions you already have in here.
Hi like you have 2 results say result1 and result2
you can make 2 foreach loop for each and store them in two different array and then
you make pass it in result and encode it.
see how it works:
foreach ($result1 as $res)
{
$result_s1[]=$res;
}
foreach($result2 as $cmd)
{
result_s1[]=$cmd;
}
$resultdata[]=array_merge($result_s1,$result_s2)

PHP: String in json parse

I am trying to parse a json. I am running this in a foreach loop and if I do the following it works:
$places = array('restaurant', 'store', 'etc')
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
However, when I do the following, i.e. I change restaurant to $places (I need to do this since I have an array of different places and I want to parse all of them in a foreach loop) it doesn't work.
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->$places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->$places[0]->geometry->location->lng;
}
Solution is changing $places to {$places}[0]
The $places array contains keywords, such as restaurant or store. So the [0] is referring to the first one in the json which is why it's needed.
Why do you have this in the first loop:
json[0]->restaurant[0]
json[0]->$restaurant[0]
But then in the next you have:
json[0]->$places[0]
json[0]->$places[0]
Perhaps you are parsing the JSON incorrectly and it should be:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->places[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->places[0]->geometry->location->lng;
}
And then in the first loop, you should do a similar edit to get rid of $restaurant[0]:
foreach ($this->placesCachingTypes as $places) {
$places_location_lat = $json_decoded->json[0]->restaurant[0]->geometry->location->lat;
$places_location_lng = $json_decoded->json[0]->restaurant[0]->geometry->location->lng;
}
Then again, unclear on what value $places has when you loop via foreach ($this->placesCachingTypes as $places) {. It does’t make sense what you would be looping through with the value of $places. And perhaps assigning that $places in the loop object of $json_decoded->json[0]-> is the source of your issues? Need more info from you to confirm this.

PHP Echo XML Attributes Without Repeating

my question has to do with PHP and XML. I would like to echo out some attributes, but echo ones that repeat only once.
Say this was the XML I was dealing with, and it was called beatles.xml:
<XML_DATA item=“TheBeatles”>
<Beatles>
<Beatle Firstname=“George” Lastname=“Harrison” Instrument=“Guitar”>Harrison, George</Beatle>
<Beatle Firstname=“John” Lastname=“Lennon” Instrument=“Guitar”>Lennon, John</Beatle>
<Beatle Firstname=“Paul” Lastname=“McCartney” Instrument=“Bass”>McCartney, Paul</Beatle>
<Beatle Firstname=“Ringo” Lastname=“Starr” Instrument=“Drums”>Starr, Ringo</Beatle>
</Beatles>
</XML_DATA>
This is the PHP I have so far:
$xml = simplexml_load_file("http://www.example.com/beatles.xml");
$beatles = $xml->Beatles->Beatle;
foreach($beatles as $beatle) {
echo $beatle->attributes()->Instrument.',';
}
I would expect this to echo out Guitar,Guitar,Bass,Drums, but I would like Guitar to only display once. How would I prevent repeat attribute values from echoing out?
Inside the foreach loop, cast the instrument name as a string and push it into an array. Once the loop finishes execution, you will have an array containing all the instrument names (with duplicates, of course). You can now use array_unique() to filter out the duplicate values from the array:
$instruments = array();
foreach($beatles as $beatle) {
$instruments[] = (string) $beatle->attributes()->Instrument;
}
$instruments = array_unique($instruments);
Demo.
$xml = simplexml_load_file("http://www.example.com/beatles.xml");
$beatles = $xml->Beatles->Beatle;
$result = array();
foreach($beatles as $beatle) {
if (!array_key_exists($beatle->attributes()->Instrument, $result)) {
$result[] = $beatle->attributes()->Instrument;
// echo $beatle->attributes()->Instrument.',';
}
}
then Loop through the $result array with foreach
Either use xpath.

Removing array index reference when using json_encode()

I have made a small application using jQuery's datepicker. I am setting unavailable dates to it from a JSON file which looks like this:
{ "dates": ["2013-12-11", "2013-12-10", "2013-12-07", "2013-12-04"] }
I would like to check if a date given is already in this list and remove it if so. My current code looks like this:
if (isset($_GET['date'])) //the date given
{
if ($_GET['roomType'] == 2)
{
$myFile = "bookedDates2.json";
$date = $_GET['date'];
if (file_exists($myFile))
{
$arr = json_decode(file_get_contents($myFile), true);
if (!in_array($date, $arr['dates']))
{
$arr['dates'][] = $_GET['date']; //adds the date into the file if it is not there already
}
else
{
foreach ($arr['dates'] as $key => $value)
{
if (in_array($date, $arr['dates']))
{
unset($arr['dates'][$key]);
array_values($arr['dates']);
}
}
}
}
$arr = json_encode($arr);
file_put_contents($myFile, $arr);
}
}
My problem here is that after I encode the array again, it looks like this:
{ "dates": ["1":"2013-12-11", "2":"2013-12-10", "3":"2013-12-07", "4":"2013-12-04"] }
Is there a way to find the date match in the JSON file and remove it, without the keys appearing after the encode?
Use array_values() for your issue:
$arr['dates'] = array_values($arr['dates']);
//..
$arr = json_encode($arr);
Why? Because you're unsetting array's key without re-ordering it. So after this the only way to keep that in JSON will be encode keys too. After applying array_values(), however, you'll get ordered keys (starting from 0) which can be encoded properly without including keys.
You are ignoring the return value of array_values in your existing attempt to reindex the array. Correct is
$arr['dates'] = array_values($arr['dates']);
The reindexing should also be moved outside the foreach loop, there is no point in reindexing multiple times.
In Laravel collections(just in case) you can do
$newArray = $collection->values()->toArray();
or
$jsonEncoded = $collection->values()->toJson();
Just pass second parameter as 'JSON_PRETTY_PRINT' to json_encode() function:
json_encode($arr, JSON_PRETTY_PRINT);
or
json_encode($arr, 128);

Function returns "Array" instead of actual output

I have this code:
function returnArray() {
$intData = array("1", "3");
return $intData[array_rand($intData)];
}
I'm trying to make a function similar to the one above.
Instead of adding integers with commas I'm trying to implode the commas with the integers.
Sort of like a dynamic version of the above using json_decode, file_get_contents, a foreach loop, array, array_rand & return
This is my code:
function Something() {
foreach (json_decode(file_get_contents('removed'), true) as $jsonArr) {
$arrData = array(implode(",", $jsonArr));
$roundData = $arrData[array_rand($arrData)];
return $roundData;
}
}
I was just wondering if I'm doing it right and if the array is correct or not.
Also it doesn't return anything from the array.
When I try to implode, it throws an error
implode invalid argument
It seems you're trying to print a random room_id from the JSON response.
The problem lies here:
$intData = array(implode(",", $arrRoomsReverse['room_id']));
You can't initialize an array like that.
Just push the room_id element to the array, like so:
$intData[] = $arrRoomsReverse['room_id'];
Now, you can simply get a random room_id outside the loop:
$intRoom = $intData[array_rand($intData)];
The function would look like:
function returnArray()
{
$str = file_get_contents('...');
$jsonArr = json_decode($str, true);
foreach ($jsonArr as $arrRoomsReverse)
{
$intData[] = $arrRoomsReverse['room_id'];
}
$intRoom = $intData[array_rand($intData)];
return $intRoom;
}
And to call the function:
echo returnArray();

Categories