PHP: Return the last json object - php

Edit
Thanks for all the input on this, I did find error in my question so modifying now. Sorry for that.
I am trying to figure out how to return the last object in the JSON string I have rendered. The two functions I am working with:
public function revision($return = false)
{
$id = $this->input->post('galleryID');
$data = array('revision_count' => $this->revision->count_revision($id) );
if($return){
return json_encode($data);
}
else {
echo json_encode($data);
}
}
public function last_revision()
{
$allRevisions = json_decode($this->revision(),true);
return end($allRevisions);
}
The issue is that end() returns error stating that 1st parameter should be array.
Thanks for any help on this.

It is important to note here that json_decode returns an instance of stdClass by default. Try using json_decode($jsonstring, true) to return the JSON as a PHP associative array.
However, You haven't included what the $this->revision() method does. Could you possibly show that portion of the code, since that is the function you are getting a return value from?
Edit:
Alright, after we saw the right function in your code, here are a couple of things I would like to say:
You have added a $return parameter to your revision method, but you aren't using it when you need to. You should change $this->revision() to $this->revision(true) in your last_revision method.
If you're going to return data from the revision() method, there's not much of a point in json_encodeing it, just to json_decode the result. Just pass back the raw data array.
Once you have changed both of these things, this should work:
$allRevisions = $this->revision(true); return end($allRevisions['revision_count']);

You can change the edit_function() to:
public function edit_revision($return = false)
{
$galleryID = $this->input->post('galleryID');
$revisionID = $this->input->post('revisionID');
$data = array('revision_images' => $this->revision->get($galleryID, $revisionID) );
if($return)
return json_encode($data);
else
echo json_encode($data);
}
and then:
public function last_revision(true)
{
$allRevisions = json_decode($this->revision());
return end($allRevisions);
}

Maybe you need convert that json output to an php array (json_decode() function), then you could get the last item with array_pop() function:
https://php.net/array_pop

Related

How to decode json in yii 1

I have following codes in my controller:
public function actionCabinet($id){
$this->render('cabinet', array('model'=>$this->loadJson($id)) );
}
public function loadJson($id)
{
$jsonfile=ChForms::model()->findByPk($id, array("select"=>"json"));
$decodedJson=json_decode($jsonfile, true);
return $decodedJson;
}
Data is saved in json field in ChForm in json format. I am going to convert it to array. When I run this application, it displays following error message:
json_decode() expects parameter 1 to be string, object given
How can I fix this error?
Please try this,
public function loadJson($id)
{
$jsonfile=ChForms::model()->findByPk($id);
$decodedJson=json_decode($jsonfile->json, true);
return $decodedJson;
}
You can use json_encode like below,
public function loadJson($id)
{
$jsonfile=ChForms::model()->findByPk($id, array("select"=>"json"));
$decodedJson=json_encode($jsonfile, true);
return $decodedJson;
}

How to call arrays from json_decode

How do I call an array from JSON_DECODE? Example:
JSON script
{
"callme":{"CallMeTo":"Called"}
}
In my case I want to be able to call it like this. (This does not work)
<?php
$json = json_decode('{"callme":{"CallMeTo":"Called"}}');
$json['callme']; // I want this to be equal to: array('CallMeTo'=>'Called')
if($json['callme']['CallMeTo'] === 'Called'){
return true;
}
?>
Have any idea how this might be a true code?
Thanks, Richard.

PHP array_map looping to itself

I´m creating an rest server using some examples in internet. The source is:
https://github.com/danucu/GUS/blob/master/restfulengine/restfulobj.php
The problem is when I´m making a call to the object, it calls itself again in the method getMyVars:
protected function getMyVars($myVars = null) {
if (empty($myVars)) {
$myVars = $this->showMyPublicsOnly();
}
if (is_array($myVars)) {
/*
* Intorc array convertit la obiect
* utilizand __METHOD__ (constanta ;) )
* pentru apelurile recursive
*/
return array_map(__METHOD__, $myVars);
} else {
// intorc array
return $myVars;
}
}
The full rest object is here:
https://github.com/danucu/GUS/blob/master/restfulengine/usertest.php
When Whe I run localhost/rest/UserREST/example it runs in a infinite loop.
I have changed the method getMyWars to:
echo $this->method."\n\n";
echo __METHOD__."\n\n";
$arReturn = array_map(__METHOD__, $myVars);
print_r($arReturn);
And I got:
GET
restObject::getMyVars
...infinitely and it never reaches: print_r($arReturn);
Maybe I´m doing something wrong.
Well, that code looks really strange, it will always call itself to the end of the times (or at least until the call stack overflows). Let me explain:
if (is_array($myVars)) { //is_array === true
return array_map(__METHOD__, $myVars); // This will call __METHOD__ (getMyVars); and pass $myVars to it (which is an array).
} else { //This will never be reached.
return $myVars;
}
Your code apparently works. What I think is happening is this:
first call: getMyVars() get passed, say, null.
this is empty, so it gets $this->showMyPublicsOnly()
this is an array, so every member of that array gets applied getMyVars()...
...but one of those values is equivalent to empty.
So if you have, say,
[ 'varOne' => 'Hello', 'varTwo' => 'World', 'varThree' => 42 ];
it will work, but
[ 'varOne' => '', ]
will loop.
You can try this:
// Only iterate on non-empty values
$myVars = array_filter($myVars);
// If there are no non-empty values...
if (empty($myVars)) {
/* ...this would loop, so we return an empty array */
return [ ];
}
return array_map(__METHOD__, $myVars);

Recursive function in php storing results without using static

I wrote the following recursive function to keep looping through result looking for $result->pages->next and calling out to curl fetching the next page and aggregating the results. Finally it returns all results as a single object.
private function pager($result) {
static $all_results;
if(isset($result->pages->next) && !empty($result->pages->next)) {
$all_results[] = $this->get_curl_request($result->pages->next);
$this->pager(end($all_results));
} else {
return $all_results;
}
}
However I really don't like using static and it feels poorly implemented and a source of technical debt. What is a more elegant way to do this?
Update
Being called with:
return $this->pager($this->get_curl_request("https://api/request/here"));
Open to changing how it is called.
Try putting $all_result as second parameter like this and add return for this line: $this->pager(end($all_results), $all_results);
Code
private function pager($result, $all_results) {
if(isset($result->pages->next) && !empty($result->pages->next)) {
$all_results[] = $this->get_curl_request($result->pages->next);
return $this->pager(end($all_results), $all_results);
} else {
return $all_results;
}
}
The above code function will return the last updated array $all_results.
Example of use:
$pager_array = $this->pager($result, array());

Returning Multiple Variables with isset()

I have a bit of code that returns the user agent, running it through a function to parse it. The code I have previously used returns only one variable from the parsing function (there are three: 'platform' 'browser' 'version'):
function my_get_user_agent($value)
{
$browser = parse_user_agent();
return isset($browser['platform']) ? $browser['platform'] : '';
}
While this code works to return the platform of the user agent, I need to append it to return all three variables in the function. I changed the first half of the code to what I assume is correct:
return isset($browser['platform'], $browser['browser'], $browser['version'])? $browser['platform'] : '';
I am unsure, however, as to what I need to do to properly return all three values. Suggestions?
You can just return the entire array:
return $browser;
Then access the values later:
$browser['platform'];
$browser['browser'];
$browser['version'];
Reading your question again, you seem to want to ensure the value are set. You can do this:
foreach($browser as $value) {
if(isset($value)) {
$data[] = $value;
}
}
return $data;
Now data will contain platform, browser, and version.
There is no tuple structure in PHP: Are there tuples in PHP?
You can either return the whole browser array, or a subset like this (this will not return the undefined values):
array_intersect_key($browser, array_flip(array("platform", "browser", "version")))
Also, if you want to set the result of your function to variables, the list construct can be handy, but you have to be sure that the values are in that order and that they exist. For that you would have to proceed like SeanWM suggested:
function my_get_user_agent($agent) {
$browser = parse_user_agent($agent);
foreach(array("platform", "browser", "version") as $value) {
$data[] = isset($browser[$value]) ? $browser[$value] : '';
}
return $data;
}
list($platform, $browser, $version) = my_get_user_agent($agent);

Categories