Evaluating a function inside php with if - php

Im trying to do a loop through a pretty large json file with this function someone else helped me with. But the code below returns with : Warning: Invalid argument supplied for foreach()
This code is executed before the function:
$file = new SplFileObject("bdfile/summoner_leagues_entries_export.json");
while (!$file->eof())
{
$json = json_decode($file->fgets(), true);
var_dump($json);
}
_
function getentry($json)
{
foreach($json as $league)
{
if($league['queue'] == 'RANKED_SOLO_5x5')
{
return $league['entries'][0];
}
return null;
}
}
$entry = getentry($json);
if(isset($entry)) echo $entry['playerOrTeamName'] . ',' . "</br>";
this is the output of var_dump($json); (just a tiny example because its a large file):
{
"_id" : ObjectId("540449a4f59600af7d285075"),
"leagues" : [{
"name" : "Cassiopeia's Hunters",
"tier" : "GOLD",
"queue" : "RANKED_SOLO_5x5",
"entries" : [{
"playerOrTeamId" : "21893177",
"playerOrTeamName" : "JoKoksa",
"division" : "III",
"leaguePoints" : NumberLong(5),
"wins" : NumberLong(99),
"isHotStreak" : false,
"isVeteran" : false,
"isFreshBlood" : false,
"isInactive" : false,
"miniSeries" : false
}],
"id" : NumberLong(21893177)
}, {
"name" : "Kayle's Patriots",
"tier" : "BRONZE",
"queue" : "RANKED_TEAM_3x3",
"entries" : [{
"playerOrTeamId" : "TEAM-ffbaccc0-b8c0-11e2-b67a-782bcb497d6f",
"playerOrTeamName" : "EloStechers",
"division" : "II",
"leaguePoints" : NumberLong(64),
"wins" : NumberLong(9),
"isHotStreak" : false,
"isVeteran" : false,
"isFreshBlood" : false,
"isInactive" : false,
"miniSeries" : false
}],
"id" : NumberLong(21893177)
}, {
"name" : "Cassiopeia's Infiltrators",
"tier" : "BRONZE",
"queue" : "RANKED_TEAM_5x5",
"entries" : [{
"playerOrTeamId" : "TEAM-ffbaccc0-b8c0-11e2-b67a-782bcb497d6f",
"playerOrTeamName" : "EloStechers",
"division" : "II",
"leaguePoints" : NumberLong(60),
"wins" : NumberLong(11),
"isHotStreak" : false,
"isVeteran" : false,
"isFreshBlood" : false,
"isInactive" : true,
"miniSeries" : false
}],
"id" : NumberLong(21893177)
}],
"summonerId" : NumberLong(21893177),
"region" : "euw",
"updatedAt" : NumberLong(1412719896)
}
EDIT 3:
$file = new SplFileObject("bdfile/summoner_leagues_entries_export.json");
while (!$file->eof()) {
$json = json_decode($file->fgets(), true);
foreach($json['leagues'] as $entry) {
echo $entry['entries'][0]['playerOrTeamName'] . ',' . $entry['tier'] . ',' . $entry['entries'][0]['division'] . ',' . $entry['entries'][0]['leaguePoints'] . ',' . $entry['entries'][0]['wins'] . "<br/>";
}
}
$file = null;
EDIT 4:
I got it fixed, if you are interested, i can paste code here.

I think your line in getentry($json)
foreach($json as $league)
should be
foreach($json['leagues'] as $league)

On reflection. That doesn't look like a vardump. Probably $json is just a string when you get into getentry.
Perhaps you need a bson_decode function before you will be able to treat it like a hash (array)
json_decode won't handle it.
There is one in mongo for php.
http://php.net/manual/en/function.bson-decode.php
But it does say "This function is very beta and entirely useless for 99% of users. It is only useful if you're doing something weird, such as writing your own driver on top of the PHP driver."

Related

How to save multiple items from JSON post in database using Yii

What I'm trying to achieve here is to save multiple items from JSON post data into database whenever there's a new registration.
I've successfully save a single registration. But if I have multiple registrations, it won't save all data passed. It will save only the first item.
Here's the JSON post data captured:
{"id" : "1514358676612-F9RM4",
"accountId" : 128768,
"eventId" : 206218,
"timestamp" : 1514358676612,
"url" : "http://hub.mymagic.my/bizzabo/bizzaboCallback",
"details" : {
"items" : [ {
"contactEmail" : "ikram#mymagic.my",
"created" : "2017-12-27T07:09:21.000+0000",
"ticketPaid" : 0,
"contactFirstName" : "Ikram",
"contactLastName" : "Khasim",
"currency" : "USD",
"validity" : "valid",
"status" : "completed",
"ticketType" : "test",
"ticketId" : 1296403,
"invoice" : false,
"contactName" : "Ikram Khasim",
"paymentStatus" : "completed",
"registrationForm" : {
"type_of_person" : "Experienced Entrepreneur",
"firstName" : "Ikram",
"organisation__instit" : "MaGIC",
"lastName" : "Khasim",
"gender" : "Male | Lelaki",
"age_group" : "22-24",
"mobileNumber" : "0193533005",
"email" : "ikram#mymagic.my",
"how_did_you_hear_abo" : "Word of mouth"
},
"type" : "ticket"
}, {
"contactEmail" : "yasmin#mymagic.my",
"created" : "2017-12-27T07:09:21.000+0000",
"ticketPaid" : 0,
"contactFirstName" : "Ikram",
"contactLastName" : "Khasim",
"currency" : "USD",
"validity" : "valid",
"status" : "completed",
"ticketType" : "test",
"ticketId" : 1296404,
"invoice" : false,
"contactName" : "Ikram Khasim",
"paymentStatus" : "completed",
"registrationForm" : {
"type_of_person" : "Experienced Entrepreneur",
"firstName" : "Ikram",
"organisation__instit" : "MaGIC",
"lastName" : "Khasim",
"gender" : "Male | Lelaki",
"age_group" : "22-24",
"mobileNumber" : "0193533005",
"email" : "yasmin#mymagic.my",
"how_did_you_hear_abo" : "Word of mouth"
},
"type" : "ticket"
} ],
"contactEmail" : "ikram#mymagic.my",
"contactFirstName" : "Ikram",
"contactLastName" : "Khasim",
"currency" : "USD",
"action" : "charge",
"status" : "completed",
"quantity" : 2,
"invoice" : false,
"contactName" : "Ikram Khasim",
"paymentStatus" : "completed",
"amount" : 0,
"orderId" : 651560
},
"type" : "orderCreated"
}
And this is the code to save the JSON post data items into database. It successfully stored the first item into the database, however didn't save the second item.
public function actionBizzaboCallback()
{
$junk = new Junk;
$junk->code = 'bizzabo-bizzaboCallback-'.time();
$junk->content .= serialize($_POST);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// fetch RAW input
$json = file_get_contents('php://input');
// expecting valid json
if (json_last_error() !== JSON_ERROR_NONE) {
$junk = new Junk;
$junk->code = 'bizzabo-getJSONError-'.time();
$junk->content = sprintf('JSON not captured at : %s', Yii::app()->params['masterDomain']);
die(header('HTTP/1.0 415 Unsupported Media Type'));
} else {
// check if registration exist
// decode json
$objects = json_decode($json);
//create new registration
$object = new EventRegistration;
$object->event_code = $objects->eventId;
$tmps = HUB::getEventCode($object->event_code);
$object->event_id = $tmps->id;
$object->event_vendor_code = 'bizzabo';
$object->registration_code = $objects->details->items[0]->ticketId;
$object->full_name = sprintf('%s %s', $objects->details->items[0]->registrationForm->firstName, $objects->details->items[0]->registrationForm->lastName);
$object->first_name = $objects->details->items[0]->registrationForm->firstName;
$object->last_name = $objects->details->items[0]->registrationForm->lastName;
$object->email = $objects->details->items[0]->registrationForm->email;
$object->date_registered = time();
$object->date_payment = time();
$object->json_original = json_decode($json,true);
$object->date_added = time();
$object->date_modified = time();
if($object->save()){
$success = 'successfully insert data into db';
}else{
$fail = $object->errors;
$status = 'failed insert data into db';
}
//create junk
$junk = new Junk;
$junk->code = 'bizzabo-getBizzaboRegistrationIntoDB-'.time();
$junk->content = sprintf('Success(%s) or Fail(%s) with error message (%s). With first name is %s and last name is %s. JSON Captured: %s', $success, $status, $fail, $object->first_name, $object->last_name, $json);
}
}
$junk->save();
}
you should iterate over the items content for save the related values eg:
} else {
// check if registration exist
// decode json
$objects = json_decode($json);
foreach( $object->details->items as $key = $value){
//create new registration
$object = new EventRegistration;
$object->event_code = $objects->eventId;
$tmps = HUB::getEventCode($object->event_code);
$object->event_id = $tmps->id;
$object->event_vendor_code = 'bizzabo';
// apply the actual item value
$object->registration_code = $value->ticketId;
$object->full_name = sprintf('%s %s',
$value->registrationForm->firstName,
$value->registrationForm->lastName);
.......
......
}

how to access json file fields [duplicate]

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 5 years ago.
{
"took" : 363,
"timed_out" : false,
"num_reduce_phases" : 15,
"_shards" : {
"total" : 7195,
"successful" : 7195,
"failed" : 0
},
"hits" : {
"total" : 35672,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"2" : {
"doc_count_error_upper_bound" : 54,
"sum_other_doc_count" : 1463,
"buckets" : [
{
"key" : "ふるさと納税",
"doc_count" : 30376
}
]
}
}
}
This is the json file . I need to access the doc_count field.
I am trying to do it like this
$trend_words = json_decode($file);
$aggregations = $trend_words->aggregations;
$buckets = $aggregations->{2}->buckets->{0};
But its not working.
Can someone help.
$trend_words = json_decode($file,true);
$aggregations = $trend_words['aggregations']['2']['buckets'][0]['doc_count'];
print_r($aggregations)
You should use ,true otherwise you will get an stdclass object and not an array you want.
try this
<?php
$sJson = '
{
"took" : 363,
"timed_out" : false,
"num_reduce_phases" : 15,
"_shards" : {
"total" : 7195,
"successful" : 7195,
"failed" : 0
},
"hits" : {
"total" : 35672,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"2" : {
"doc_count_error_upper_bound" : 54,
"sum_other_doc_count" : 1463,
"buckets" : [
{
"key" : "ふるさと納税",
"doc_count" : 30376
}
]
}
}
}
';
$aJson = json_decode($sJson, true);
echo $aJson['aggregations'][2]['buckets'][0]['doc_count'];
https://3v4l.org/kHfdo
Here is the answer, As the buckets increases you need to have a loop through to read all the buckets
$trend_words = json_decode($file, true);
$aggregations = $trend_words['aggregations'][2];
$buckets = array();
foreach($aggregations as $element)
$buckets[] = $element['buckets'];
print_r($buckets);
Make Json to array and try
$trend_words = json_decode($file, true);
$aggregations = $trend_words['aggregations'];
$buckets =$aggregations[2]['buckets'][0];

Json to url with php

In my $output there is this:
{
"status" : "success",
"data" : {
"network" : "BTC",
"addresses" : [
{
"user_id" : 0,
"address" : "3ABR5GohqyXzf2zebYwjmLuwV7vtFZw1BZ",
"label" : "default",
"available_balance" : "0.00000000",
"pending_received_balance" : "0.00000000"
}
]
}
}
But now I want it to get to redirect like:
https://example.com/index.php?status=succes&network=BTC
etc. etc.
But $output can change to like:
{
"status" : "success",
"data" : {
"network" : "BTC",
"available_balance" : "0.00000000",
"pending_received_balance" : "0.00000000"
}
}
But then I still want it to work.
I don't know PHP enough for this, so I want to ask:
How to do this?
Simply json_decode() and access the status and network properties:
$decoded = json_decode($output);
header('Location: https://example.com/index.php?status=' . urlencode($decoded->status) . '&network=' . urlencode($decoded->data->network));
exit();
Get the data in the json as an array:
$url = 'https://example.com/index.php?status=' . $status;
foreach($data as $param->$value) {
$url += '&' . $param . '=' . $value
}
header('Location:' $url);
Been a while since i've worked in php but this should handle a varying amount of parameters.

WordPress get json data single value

Trying to get the single value from google finances api. I can retrieve the data perfectly however when I try to echo out a single value it doesn't seem to work. Can anyone help?
My code is:
$request = wp_remote_get('http://www.google.com/finance/info?q=NASDAQ%3aGOOG', $args );
$price = wp_remote_retrieve_body( $request );
print_r($price);
The output is:
// [
{
"id": "304466804484872"
,"t" : "GOOG"
,"e" : "NASDAQ"
,"l" : "533.75"
,"l_fix" : "533.75"
,"l_cur" : "533.75"
,"s": "2"
,"ltt":"4:01PM EST"
,"lt" : "Dec 2, 4:01PM EST"
,"lt_dts" : "2014-12-02T16:01:56Z"
,"c" : "-0.05"
,"c_fix" : "-0.05"
,"cp" : "-0.01"
,"cp_fix" : "-0.01"
,"ccol" : "chr"
,"pcls_fix" : "533.8"
,"el": "533.00"
,"el_fix": "533.00"
,"el_cur": "533.00"
,"elt" : "Dec 2, 7:59PM EST"
,"ec" : "-0.75"
,"ec_fix" : "-0.75"
,"ecp" : "-0.14"
,"ecp_fix" : "-0.14"
,"eccol" : "chr"
,"div" : ""
,"yld" : ""
}
]
I've tried echoing out the single value, adding a foreach statement and then echoing out the value based on 'l_fix' and the 'id', and also tried splitting the string up but it wouldn't work.
Thanks
Do it:
$request = wp_remote_get('http://www.google.com/finance/info?q=NASDAQ%3aGOOG', $args );
$data = wp_remote_retrieve_body( $request );
$data = str_replace('//','',$data);
$data = json_decode($data);
$price = $data[0]; // $price = array_shift($data);
print $price->l_fix .....
Google APIs (in this specific case) return JSON with two first chars ('//').

Can't get data from mongoDB

I create function to get data from mongoDB by PHP code. But It seem not working well.
let's see my code
function updateperformancescore($timepf)
{
$mon = new Mongo('mongodb://127.0.0.1:27017');
$dbs = $mon->selectDB('bitdindatabase');
$col = $dbs->selectCollection('bd_performance_score');
$query2 = array("user_ID"=>"999");
echo "<br>query__".$query2["user_ID"];
$data2 = $col->find($query2,true);
echo "<br>count___".count($data2)."<br>";
echo "check is_object--".is_object($data2)."<br>";
//echo "--".$data2["user_ID"]."<br>";
error_reporting(E_ALL ^ E_NOTICE);
foreach ($data2 as $obj)
{
echo "aaaa";
$which = array("user_ID"=>$obj["user_ID"],"time"=>$obj["ps_avgtime"],"slug"=>$obj["lesson_slug"]);
echo json_encode($which);
}
and webpage show only
query_999
count__1
check is_object--1
but my data in mongo is
{ "_id" : ObjectId("501e768eefbdb8637e2b00c8"), "user_ID" : 999, "lesson_slug" : 999, "ps_avgtime" : 999 }
{ "_id" : ObjectId("501e7698efbdb8637e2b00c9"), "user_ID" : 999, "lesson_slug" : 998, "ps_avgtime" : 888 }
{ "_id" : ObjectId("501e76a1efbdb8637e2b00ca"), "user_ID" : 999, "lesson_slug" : 997, "ps_avgtime" : 777 }
{ "_id" : ObjectId("501e76a9efbdb8637e2b00cb"), "user_ID" : 999, "lesson_slug" : 996, "ps_avgtime" : 77 }
{ "_id" : ObjectId("501e76b6efbdb8637e2b00cc"), "user_ID" : 999, "lesson_slug" : 995, "ps_avgtime" : 555 }
{ "_id" : ObjectId("501e76c0efbdb8637e2b00cd"), "user_ID" : 999, "lesson_slug" : 994, "ps_avgtime" : 444 }
{ "_id" : ObjectId("501e76caefbdb8637e2b00ce"), "user_ID" : 999, "lesson_slug" : 993, "ps_avgtime" : 333 }
{ "_id" : ObjectId("501e76d3efbdb8637e2b00cf"), "user_ID" : 999, "lesson_slug" : 992, "ps_avgtime" : 222 }
{ "_id" : ObjectId("501e76dcefbdb8637e2b00d0"), "user_ID" : 999, "lesson_slug" : 991, "ps_avgtime" : 111 }
{ "_id" : ObjectId("501e76e6efbdb8637e2b00d1"), "user_ID" : 999, "lesson_slug" : 990, "ps_avgtime" : 1 }
Why it's not going into foreach ? And What's wrong with this code and How I get data correctly.
help or guide me please :)
edit
I just error_log and It show
Fatal error: Uncaught exception 'MongoException' with message 'The MongoCursor object has not been correctly initialized by its constructor' in /var/www/web/sendanswer.php:92 Stack trace: #0 /var/www/web/sendanswer.php(92): MongoCursor->rewind() #1 /var/www/web/sendanswer.php(343): sendanswer->updateperformancescore(4.4269230365753) #2 {main} Next exception 'MongoException' with message 'The MongoCursor object has not been correctly initialized by its constructor' in /var/www/web/sendanswer.php:92 Stack trace: #0 /var/www/web/sendanswer.php(92): MongoCursor->rewind() #1 /var/www/web/sendanswer.php(343): sendanswer->updateperformancescore(4.4269230365753) #2 {main} thrown in /var/www/web/sendanswer.php on line 92
what does it mean ??
edit
That means "Probably your Mongo object is not connected to a database server."
What I see is an error in datatypes.
In database user_ID is an integer,
in your PHP query, it is a string.
Try:
$query2 = array("user_ID"=> 999);
instead of :
$query2 = array("user_ID"=>"999");
PHP may be easy on datatypes, but I am not sure about Mongodb and its PHP driver.
Also there is an incorrect parameter in your find statement. Remove the true as it should be an array of fields, not a bool
This code works correctly :
<?php
$mon = new Mongo('mongodb://127.0.0.1:27017');
$dbs = $mon->selectDB('my_db');
$col = $dbs->selectCollection('newColl');
$query2 = array("user_ID"=> 999);
echo "<br>query__".$query2["user_ID"];
$data2 = $col->find($query2);
error_reporting(E_ALL ^ E_NOTICE);
foreach ($data2 as $obj)
{
$which = array("user_ID"=>$obj["user_ID"],
"time"=>$obj["ps_avgtime"],
"slug"=>$obj["lesson_slug"]);
echo json_encode($which);
echo PHP_EOL ;
}
?>
Output:
[......]$ php testmongo.php
<br>query__999{"user_ID":999,"time":999,"slug":999}
{"user_ID":999,"time":999,"slug":999}
{"user_ID":999,"time":339,"slug":999}
{"user_ID":999,"time":339,"slug":5599}

Categories