string element of array is not able to access after json decode - json

this is my code for decode array
$transfer = '{"type": "BALANCE","status": "REJECTED"}'; $json = json_decode($transfer); echo $json->status;
it is not displaying status value.
if I change status to integer value.
$transfer = '{"type": "BALANCE","status": "1234"}';
then it is displaying status value as 1234.
how to display status value if its in string format.

This is working fine
<?php
$transfer = '{"type": "BALANCE","status": "REJECTED"}';
$json = json_decode($transfer);
echo $json->status; //displays REJECTED
?>

Related

Azure Functions: Powershell Push-OutputBinding format JSON

I have used below code in my azure PowerShell HTTP function. On triggering this function, I receive JSON body but not as in the same order I have provided in code. Please let me know how can I receive JSON body in response as in same order I have coded i.e. {"Status": "val", "Msg": "val", "Value": "val"}
Push-OutputBinding -Name Response -Value ([HttpResponseContext]#{
StatusCode = [HttpStatusCode]::OK
Headers = #{
"Content-type" = "application/json"
}
Body = #{
"Status" = $status
"Msg" = $body
"Value" = $val
} | ConvertTo-Json
})
The order of keys in a hash table is not determined.
Use an ordered dictionary instead of a hashtable.
This will preserve the order of your keys as you intended them.
To do so, simply add the [Ordered] type in front of your body hashtable.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]#{
StatusCode = [HttpStatusCode]::OK
Headers = #{
"Content-type" = "application/json"
}
# Will keep the order of the keys as specified.
Body = [Ordered]#{
"Status" = $status
"Msg" = $body
"Value" = $val
} | ConvertTo-Json
})
Beginning in PowerShell 3.0, you can use the [ordered] attribute to
create an ordered dictionary
(System.Collections.Specialized.OrderedDictionary) in PowerShell.
Ordered dictionaries differ from hash tables in that the keys always
appear in the order in which you list them. The order of keys in a
hash table is not determined.
Source

invalid json response in php when json response inside json response

i have try to print json response but "" are added to my json response
i tried below code php and id generated by drupal field
<?php
$data = array("title"=>"test","body"=>"test body");
$php = json_encode($data,JSON_FORCE_OBJECT);
echo json_encode(array("php"=>$php,"id"=>10));
?>
output :
{"php":"{\"title\":\"test\",\"body\":\"test body\"}","id":10}
but i want output like below
{"php":{"title":"test","body":"test body"},"id":10}
i added some more code for above problem
{"php":"{\"title\":\"test\",\"body\":\"test body\"}","id":10}
why not remove json_encode from echo json_encode($php);
how i can get above output` second time
You're encoding in JSON two times :
$data = array("title"=>"test","body"=>"test body");
$php = json_encode($data,JSON_FORCE_OBJECT);
echo $php ; // remove json_encode() here
After question edit:
$data = array("title"=>"test","body"=>"test body");
echo json_encode(array("php"=>$data,"id"=>10));
You can also simply do this,
<?php
$data = array("title"=>"test","body"=>"test body");
echo json_encode(array("php"=>$data,"id"=>10));
?>

Processing results from fatfree DB SQL Mapper for json encoding

I'm having trouble processing the returned results from a DB SQL Mapper into a recognizable json encoded array.
function apiCheckSupplyId() {
/*refer to the model Xrefs*/
$supply_id = $this->f3->get('GET.supply_id');
$xref = new Xrefs($this->tongpodb);
$supply = $xref->getBySupplyId( $supply_id );
if ( count( $supply ) == 0 ) {
$this->logger->write('no xref found for supply_id=' .$supply_id);
$supply = array( array('id'=>0) );
echo json_encode( $supply );
} else {
$json = array();
foreach ($supply as $row){
$item = array();
foreach($row as $key => $value){
$item[$key] = $value;
}
array_push($json, $item);
}
$this->logger->write('xref found for supply_id=' .$supply_id.json_encode( $json ) );
echo json_encode( $json );
}
}
This is the method I am using but it seems very clunky to me. Is there a better way?
Assuming the getBySupplyId returns an array of Xref mappers, you could simplify the whole thing like this:
function apiCheckSupplyId() {
$supply_id = $this->f3->get('GET.supply_id');
$xref = new Xrefs($this->tongpodb);
$xrefs = $xref->getBySupplyId($supply_id);
echo json_encode(array_map([$xref,'cast'],$xrefs));
$this->logger->write(sprintf('%d xrefs found for supply_id=%d',count($xrefs),$supply_id));
}
Explanation:
The $xrefs variable contains an array of mappers. Each mapper being an object, you have to cast it to an array before encoding it to JSON. This can be done in one line by mapping the $xref->cast() method to each record: array_map([$xref,'cast'],$xrefs).
If you're not confident with that syntax, you can loop through each record and cast it:
$cast=[];
foreach ($xrefs as $x)
$cast[]=$x->cast();
echo json_encode($cast);
The result is the same.
The advantage of using cast() other just reading each value (as you're doing in your original script) is that it includes virtual fields as well.

Retrieve particular field from serialized data

Suppose I have following data :
a:1:{s:4:"date";a:3:{s:2:"mm";s:2:"12";s:2:"dd";s:2:"06";s:2:"yy";s:4:"1991";}}
I want the value of mm and dd from that serialized string.
I have following query to retrieve above data :
$birthday = "select meta_key, meta_value from $wpdb->usermeta where meta_key='pie_date_5'";
$user_birthday = $wpdb->get_results($birthday);
foreach($user_birthday as $ubday){
$ubd = $ubday->meta_value; echo $ubd;
echo json_decode($ubd[0]->mm);
}
I am not able to do that simple thing. Please help me out.
You have to use unserialize instead of json_decode because it's a serialized string.
So you could try something like this:
$user_birthday = 'a:1:{s:4:"date";a:3:{s:2:"mm";s:2:"12";s:2:"dd";s:2:"06";s:2:"yy";s:4:"1991";}}'; //the serialized string you get from your query
$upday = unserialize( $user_birthday );
echo $upday['date']['mm'] . PHP_EOL;
echo $upday['date']['dd'];
EDIT: If you want to read all properties from the $upday array you could use a foreach-loop
foreach ( $upday['date'] as $key => $value ) :
echo $key . ' = ' . $value . PHP_EOL;
endforeach;

Codeigniter random row mysql error- Object of class CI_DB_mysqli_result could not be converted to string

function random()
{
$anketadb = $this->load->database('anketa',TRUE);
$br = $anketadb->count_all_results('anketadata');
$nmb = mt_rand(1,$br);
if ($nmb != 1){
$nmb = $nmb - 1;
}
$count = $anketadb->get('anketadata', 1, $nmb);
return $count;
}
Why this code when i echo it in View returns ERROR:
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysqli_result could not be converted to
string
Filename: ankete/rezultatiankete.php
Line Number: 52
You should have shown us more code (controller, view etc), anyways, in your example you are using
return $count;
in this case $count; is an object and to echo it's fields you have to loop in your view like
foreach ($count->result() as $row)
{
echo $row->fieldname; // rerplace the fieldname with a real field/column name of your database
}
so if you are trying to echo the $count then you are making a mistake, it's an object, read more here.
echo doesnot work for objects use print_r(returned value) to output objects,arrays
to fetch a random column use SELECT * FROM table ORDER BY RAND() LIMIT 0,1;