php json_decode VS Laravel Tinker json_decode - php

i have a problem about php json_decode, now i have a json string like this
"{\"client_id\":\"yunniao\",\"client_secret\":\"sdfW234eDtjkuDFityDu345JYyuk5Jom\",\"insurance_applicant_id\":1,\"policyholder\":\"\\u5317\\u4eac\\u4e91\\u4e2d\\u5c0f\\u9e1f\\u79d1\\u6280\\u6709\\u9650\\u516c\\u53f8\",\"ower_name\":\"\\u8bd7\\u6768\\u8fd0\\u529b\\u4e8c\",\"plate_no\":\"\\u4eacM00002\",\"trade_no\":\"2932848\",\"cargo_type\":\"\\u4e34\\u65f6\\u4efb\\u52a1-\\u6709SOP\",\"cargo_amount\":\"1-1\",\"cargo_number_min\":1,\"cargo_number_max\":1,\"start_place\":\"\\u5367\\u9f99\\u5c0f\\u533a\",\"end_place\":\"\\u4e3b\\u4efb\\u52a1-\\u6709SOP\",\"effect_date\":\"2017-07-01T00:08:44+08:00\",\"coverage\":100000,\"freight\":\"3000\"}"
is a very json string,;
i put this in Laravel artisan tiker the above string return me like this, it's a image, but it's not show in here:
but in the php interactive command line, the json string give me nothing, the result like behind image;
i'm tried a lot of possibilities;
i tried to put above code in my Laravel project, then test the file, it give me null;
i googled so many times, but there is no answer;
it's all failed, now i'm here, i think i want help!
thanks for any help and workround.
===================================================================
Hello guys, i have been resolved this, i used eval, the eval like this
$param = "{\"insurance_applicant_id\":1,\"plate_no\":\"\\u4eacA11113\",\"trade_no\":86254,\"cargo_type\":\"\",\"cargo_number_min\":0,\"cargo_number_max\":0,\"cargo_amount\":\"0~0\",\"start_place\":\"\\u897f\\u82d1\",\"end_place\":\"\\u914d\\u9001\\u533a\\u57df\\u63cf\\u8ff0\",\"effect_date\":\"2016-01-09 14:54:04\",\"coverage\":0,\"freight\":79200}";
eval("\$param = \"$param\";");
$decodeValue = json_decode($param);
hope this help for other people, i closed this, thanks everybody again!

The interactive PHP console simply does not automatically output the value of the last evaluated expression. Your PHP code doesn't echo anything, so there's no output. You need to print_r(json_decode(...)) to see something.

Try this
$json = "{\"client_id\":\"yunniao\",\"client_secret\":\"sdfW234eDtjkuDFityDu345JYyuk5Jom\",\"insurance_applicant_id\":1,\"policyholder\":\"\\u5317\\u4eac\\u4e91\\u4e2d\\u5c0f\\u9e1f\\u79d1\\u6280\\u6709\\u9650\\u516c\\u53f8\",\"ower_name\":\"\\u8bd7\\u6768\\u8fd0\\u529b\\u4e8c\",\"plate_no\":\"\\u4eacM00002\",\"trade_no\":\"2932848\",\"cargo_type\":\"\\u4e34\\u65f6\\u4efb\\u52a1-\\u6709SOP\",\"cargo_amount\":\"1-1\",\"cargo_number_min\":1,\"cargo_number_max\":1,\"start_place\":\"\\u5367\\u9f99\\u5c0f\\u533a\",\"end_place\":\"\\u4e3b\\u4efb\\u52a1-\\u6709SOP\",\"effect_date\":\"2017-07-01T00:08:44+08:00\",\"coverage\":100000,\"freight\":\"3000\"}";
$decoded = json_decode($json, true);
It will give you decoded json in array form like this
[
"client_id" => "yunniao",
"client_secret" => "sdfW234eDtjkuDFityDu345JYyuk5Jom",
"insurance_applicant_id" => 1,
"policyholder" => "北京云中小鸟科技有限公司",
"ower_name" => "诗杨运力二",
"plate_no" => "京M00002",
"trade_no" => "2932848",
"cargo_type" => "临时任务-有SOP",
"cargo_amount" => "1-1",
"cargo_number_min" => 1,
"cargo_number_max" => 1,
"start_place" => "卧龙小区",
"end_place" => "主任务-有SOP",
"effect_date" => "2017-07-01T00:08:44+08:00",
"coverage" => 100000,
"freight" => "3000",
]

Related

php class in an array

I have a php file where I have an array with some data in classes like this: (in javascript)
array = [
{engine: "V6",
capacity: 2.5,
hp: 300
}]
I tried to put this into a php file but it gave me 500 error
$array = [{engine => "V6",
capacity=> 2.5,
hp=> 300}];
I think I may be doing something wrong over here, could someone confirm?
You can't just translate JavaScript code into PHP without understanding the syntax of both languages.
In JavaScript, this creates an array containing an object:
var array = [
{
engine: "V6",
capacity: 2.5,
hp: 300
}
]
In PHP, the common equivalent would be an array containing another (associative) array, which would be written like this:
$array = [
[
'engine' => "V6",
'capacity' => 2.5,
'hp' => 300
]
];
As an aside, since it's been mentioned elsewhere on this page, you could also write the same thing in JSON like this:
[
{
"engine": "V6",
"capacity": 2.5,
"hp": 300
}
]
If you called JSON.stringify(array) in JavaScript, or json_encode($array) in PHP, that's how the JSON string you'd get would look.
The JSON looks very similar to the JavaScript, because JSON's syntax was based on JavaScript's. In fact, the above would be valid JavaScript code, and you can use (arguably, abuse) json_encode as a way to generate JavaScript code using PHP.
Note that none of these contains any kind of "class" - a class is a way of defining a type of object, from which you want to make several instances.
You are mixing PHP with JSOL or JSON. PHP doesn't read JSOL nor JSON natively.
<?php
$array = [
[
'engine' => 'V6',
'capacity' => 2.5,
'hp' => 300
],
];
echo json_encode($array);
See https://3v4l.org/5b9V1

Accessing a child node using JSON within PHP and file_get_contents()

OK I am stumped.
I have tried numerous different approaches and I've spent the best part of a good few hours searching to no avail to my exact situation, that or I am tired and blind.
Here is the raw json pulled from a URI using file_get_contents():
{"id":"XXX","name":"Customer1","os":"CentOS Linux 7.3.1611 Core","cpu_type":"Intel(R) Xeon(R) CPU E3-1245 V2 # 3.40GHz","networking_v4":[{"addr":"xxx.xxx.xxx.xxx","if":"eth0"}],"networking_v6":[{"addr":"xxxx","if":"eth0"},{"addr":"xxxx","if":"eth0"}],"agent_version":0.96,"status":"up","last_update":1505949230,"first_update":1500588943,"notifications_count":8,"ip_whois":{"ip":"xxx.xxx.xxx.xxx","hostname":"xxx","city":"Garwood","region":"New Jersey","country":"US","loc":"xxx","org":"AS20473 Choopa, LLC","postal":"xxx"},"additional_fields":[{"value":"xxx","key":"Datacenter"},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""},{"value":"","key":""}]}
As you can see its a pretty simple request and I have every bit of data except those nested within networking_v4 and networking_v6.
I tried to access those like so:
'ipv4' => $json->networking_v4->addr,
'ipv4dev' => $json->networking_v4->if,
'ipv6' => $json->networking_v6->addr,
'ipv6dev' => $json->networking_v6->if,
Here is the full snapshot of code in its entirety:
$content = file_get_contents($url);
$json = json_decode($content);
$server_lastupd = $json->last_update;
$server_firstupd = $json->first_update;
$server = array(
'id' => $json->id,
'name' => $json->name,
'os' => $json->os,
'cputype' => $json->cpu_type,
'ipv4' => $json->networking_v4->addr,
'ipv4dev' => $json->networking_v4->if,
'ipv6' => $json->networking_v6->addr,
'ipv6dev' => $json->networking_v6->if,
'status' => $json->status,
'lastupd' => $json->$server_lastupd,
'firstupd' => $json->$server_firstupd,
'notifications' => $json->notifications_count,
'ip' => $json->ip_whois->ip,
'hostname' => $json->ip_whois->hostname,
'city' => $json->ip_whois->city,
'region' => $json->ip_whois->region,
'country' => $json->ip_whois->country,
'loc' => $json->ip_whois->loc,
'org' => $json->ip_whois->org,
'postal' => $json->ip_whois->postal,
'dctag' => $json->additonal_fields->dctag,
'source' => "XXX"
);
return $server;
So my issue is I appear to be unable to access the child content within networking_v4 and networking_v6.
Any help on this would be massively appreciated, its stumped me for the best part of 6 hours last night and a few more today, so I give in, someone please show me the light!
Many thanks :)
It looks like those are nested in arrays from the [{"key':"value"},{"key":"value"}] square brackets. have you tried
ipv4 => $json->networking_v4[0]->addr,
Try $json->networking_v4[0]->addr.
Both the networking_v4 and the networking_v6 keys point to arrays, so you need to pick which index you want to look at. The former only has one element, so it's easy to pick index 0, but the latter has multiple elements, so you'll need to figure out which one you want.

PHP Mongo MapReduce - How to Call Server Loaded JavaScript Functions

First, I want to say that this is more of a PHP Mongo Driver issue than MongoDB issue.
I have a problem with calling MapReduce through PHP. I have 3 custom functions inside Mongo for MapReduce: mapItems, reduceItems, finalizeItems.
When I test my functions from inside Mongo Shell, everything works great:
db.loadServerScripts();
db.runCommand({
mapreduce: 'items',
map: mapItems,
reduce: reduceItems,
finalize: finalizeItems,
out: {inline: 1},
scope: {members: {a1: 0, a2: 0}
});
Now when I try to do the same in PHP Mongo Driver, nothing works.
$db->command([
'mapreduce' => 'items',
'map' => 'mapItems',
'reduce' => 'reduceItems',
'finalize' => 'finalizeItems',
'out' => ['inline' => 1],
'scope' => ['members' => ['a1' => 0, 'a2' => 0]]
]);
I thought maybe I need to use MongoCode for the functions, but that still didn't work:
$db->command([
'mapreduce' => 'items',
'map' => new \MongoCode('mapItems'),
'reduce' => new \MongoCode('reduceItems'),
'finalize' => new \MongoCode('finalizeItems'),
'out' => ['inline' => 1],
'scope' => ['members' => ['a1' => 0, 'a2' => 0]]
]);
Then I thought maybe the PHP driver is being stupid, so I copy pasted the functions into PHP and tried them:
$db->command([
'mapreduce' => 'items',
'map' => new \MongoCode($mapFn),
'reduce' => new \MongoCode($reduceFn),
'finalize' => new \MongoCode($finalizeFn),
'out' => ['inline' => 1],
'scope' => ['members' => ['a1' => 0, 'a2' => 0]]
]);
And this worked.
How do I need to pass the internal functions to Mongo through PHP?
What you have done so far
This is a classic case of things not working how you seem to think they work. Let's break this down logically for everyone to understand.
So what you clearly have done to date is create some JavaScript function definitions and stored them in system.js. Now anything that has been stored in such a way can be called by server side JavaScript operations, which is fine. An example:
db.system.js.save({
"_id": squareThis",
"value": function(x) { return x*x; }
})
db.test.insert({ "a": 3 ))
db.test.find(function() { return squareThis(this.a) == 9 })
So that works as expected where the "server" can use the function. Not if you did this ( as you mention earlier ) :
db.loadServerScripts();
Now any functions in system.js are now available for the "shell client" to use as well. So you can now do this in the JavaScript REPL:
> squareThis(3) == 9
true
What you are doing wrong
Now you want to code with PHP. So you go to call your JavaScript methods you created on the "server" from your PHP code and you try this:
'map' => new \MongoCode('mapItems'),
So what is MongoCode? Well it basically defines a BSON type for a code reference ( expected to be JavaScript ) and sends that to the server.
The clear problem here is that "mapItems" is not JavaScript code. You "shell client" recognized that, but only after calling db.loadServerScripts(), which of course it can do, because that client understands JavaScript.
The same is true for the earlier attempt. Your PHP mapReduce command expects to have MongoCode objects that actually contain valid JavaScript. These are going to be sent to the server where it can acutally call functions defined there, but you still need to provide the mapReduce command with "real code" that does something.
Fixing It
Fortunately there is a way around this, in that you can basically "define a function to call a function" essentially "wrapping" the method calls so the "server" loaded code can be called.
The sytax varies depending on if the function is supposed to return anything so:
$db->command([
'mapreduce' => 'items',
'map' => new \MongoCode('function() { mapItems(this) }'),
'reduce' => new \MongoCode('function(key,values) { return reduceItems(key,values) }'),
'finalize' => new \MongoCode('function(key,value) { return finalizeItems(key,value)}'),
'out' => ['inline' => 1],
'scope' => ['members' => ['a1' => 0, 'a2' => 0]]
]);
So now your PHP mapReduce command sends up it's "packaged command" with valid JavaScript functions attached to the appropriate method stages. These "code wrappers" execute on the "server" and can then call the respective "server" methods that are stored in system.js.
The reason for the explicit argument passing i.e
function(key,values){ serverFunction(key,values) }
Is because your "wrappers" need to create the same sort of "signatures" as expected by the functions of "mapReduce" in general. And since they are "calling" the other methods "server side", then you need to "pass-through" the expected parameters.
This also has another implication for the "mapper" function. You are likely referring to all document content through the this context of JavaScript objects. Once you do this then you cannot do that anymore and will need to "explicitly" define a document argument to your "mapper"
db.system.js({
"_id": "mapper",
"value": function(doc) {
// use doc instead of this
}
And then even from the Mongo Shell you will also need to call like this:
db.runCommand({
"mapReduce": "items",
"mapper": function() { mapper(this) }
In order for the logic to work.
So server side functions are not really what you thought they are. You can use them, but you need to follow the rules of how they can be used.
In general it is probably better that you simply just code all of these up in your client rather than jump through all the hoops. It is afterall "JavaScript" execution for which the only language is "JavaScript", so that is why alternate methods of processing are generally preferred as long as they can be applied.
And if your document structure needs JavaScript processing, then you probably have your document structure wrong in the first place. So the better case here is "re-evaluate" your structure and processing needs to get you "cleaner" and "faster" code.

substr[0] not working, returning different characters to echoed string

I am using wp_remote_post to post some information to an API like so...
$response = wp_remote_post( $validation_url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => array(),
'body' => $fields,
'cookies' => array()
)
);
If I then do this...
$validationresponse = $response['body'];
echo $validationresponse;
Then it correctly returns the content of $response['body'] which looks like this....
100Successfull Validation
but if I then try and do this...
echo substr($validationresponse, 1);
To return the first character then it doesn't work, instead it returns this...
?xml version="1.0"?>
Am I doing something wrong, can anyone suggest whats happening?
If you want to just substract first character go with:
echo $validationresponse[0];
For your code to work (it returns rest of string starting at second character) you should first check if $validationresponse has length of 2 or more characters. Also, try to var_dump() (use var_dump() instead of print_r() as var_dump shows NULLs and stuff) result instead of echoeing it as reference says:
Returns the extracted part of string; or FALSE on failure, or an empty string.
Also, post any errors if you got any.
As you've written it - echo substr($validationresponse, 1); - would return the rest of the string starting with the second character. If you want a single character you would use - echo substr($validationresponse, 1, 1);. See http://php.net/substr. Is that the situation you see?

Symfony convert entity to json format by looping foreach

I have a little REST API in my project. And ofcourse i use json as my return data to work with.
I am using symfony in the backend and angularJs in the frontend. At the moment i convert my entity to json by looping true my result and filling an data array to return as json.
EXAMPLE:
public function getAction($id)
{
$em = $this->getDoctrine()->getManager();
$warehouseId = $this->get('session')->get('warehouse');
$warehouse = $em->getRepository('BubbleMainBundle:Warehouse')->find($warehouseId);
$trip = $em->getRepository('BubbleMainBundle:Trip')->find($id);
$data = array(
'id' => $trip->getId(),
'driver' => $trip->getDriver(),
'status' => $trip->getStatus(),
'date' => $trip->getPlanningDate()->format('Y-m-d')
);
if ( count($trip->getStops()) > 0 ) {
foreach($trip->getStops() as $stop)
{
$data['assignedStops'][] = array(
'id' => $stop->getId(),
'status' => $stop->getStatus(),
'date' => $stop->getDeliveryDate()->format('Y-m-d'),
'sort' => $stop->getSort(),
'company' => array(
'name' => $stop->getToCompany()->getName(),
'lat' => $stop->getToCompany()->getLat(),
'lng' => $stop->getToCompany()->getLng(),
'address' => $stop->getToCompany()->getAddress(),
'zip' => $stop->getToCompany()->getZip()
),
);
}
} else {
$data['assignedStops'][] = '';
}
$response = new jsonResponse();
$response->setData($data);
return $response;
}
This works. But sometimes i have have (google chrome timeline) waiting responses of 6 seconds for just a simple query and json response.
Is looping true the entity to much? Or do i need another approach for converting my entities to json format?
thx anthony,
If you are using PHP 5.4 or above then considering using the JsonSerializable interface with your entities:
http://www.php.net/manual/en/class.jsonserializable.php
This will allow you to control how your entities are converted to JSON which will allow you to call json_encode directly on your entities without having to loop through and convert them to arrays.
As for the performance issue you'd need to profile your script to find out where the performance bottleneck is. From looking at your code one potential issue that you might want to look into is to make sure you are fetching all the data in your original query (i.e stops and companies) and you are not executing additional queries in the foreach loop to fetch the missing stop and company data.
I recommend you (since you are using Symfony2 as a backend and you need an API) to definitely try out this bundle... It's easy to use and to setup and as an extra you can also generate a nice documentation for it.
It will speed up your development and code.

Categories