php class in an array - php

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

Related

Passing Form-data Array from one function to another function in same controller

I have a multidimensional array containing data from a form and I need this array in another Controller in the same controller to continue working with it, but I don't know how I do that.
The array can look like this example:
array [
"absender" => "Maxim Ivan",
"email" => "maximivan#example.com",
"telefon" => "1234567890",
"fax" => null,
"grund" => "Gehaltserhöhung",
"termin" => [
0 => [
"person" => "Some Name",
"meeting" => "10.05"
],
1 => [
"person" => "Another Name",
"meeting" => "18.05"
],
2 => [
"person" => "Again another name",
"next-possible-meeting" => "1"
],
3 => [
"person" => "And again",
"next-possible-meeting" => "1"
],
],
"bemerkung" => "some notes by Maxim"
]
This array is created(and the input data validated) in the store-method of the 'TerminController'.
This method will return a view where all of this data gets displayed again, to let the user check the info and can then add a document.
When the document is added and the data gets submitted with an input-button the upload-method in the same Controller gets called.
And there's where I need the array with the form-data to go on working with it.
But how do I achieve passing the array through to the next function that is only called with an input-button.
First approach was to save the array into the session, which did even work even though it was hard due to the multidimensional; but it's a really ugly solution.
Should I save the input data into a database in the store-method and fetch it again in the upload-method?
Or is it somehow possible to pass the array through the Controllers/ make it accessible in the upload-Controller even though it gets created in another one?
I have also heard something about using serialize()and unserialize(), but I'm not exactly sure how this could help me..
Or maybe there's another and even better solution I just don't think of?
I'd appreciate all the help I can get.
The array varies, it can be 17 arrays nested in 'termin' but I can also be just one.
You can store it in the cache:
Cache::put('multiArray', $multiArray); //put array in cache
$array = Cache::get('multiArray'); //retreive from cache

php json_decode VS Laravel Tinker json_decode

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",
]

How to set Affects Version field via JIRA REST API - PHP

I would like to update the affects versions field via JIRA REST API. But I'm getting an error:
{"errorMessages":[],"errors":{"versions":"Affects Version/s is required."}}
I have the following code:
public function requestBug($summary, $components, $affectsVersions, $fixVersions, $assignee, $environment, $description)
{
$json = Array ( "fields" => Array (
"project" => Array( "id" => 10051),
"summary" => $summary,
"issuetype" => Array ( "name" => "Bug" ),
"components" =>Array(0 => Array("id" => $components)),
"versions" =>Array(0 =>Array("affectsVersion" => $affectsVersions)),
"versions" =>Array(0 =>Array("fixVersion" =>$fixVersions)),
"assignee" => Array("name" => "$assignee"),
"environment" => "$environment",
"description" =>$description
)
);
return $json;
}
Please assist. I came across this link, but doesnt work for me
I had the same problem and the given answer (even with links provided) did not help me much. I played around with all sorts of variations and finally this piece of JSON worked to change the affected version of an item to "Version 2.0.0":
"versions":
[
{ "Affects Version/s" : "Version 2.0.0"
},
{ "name": "Version 2.0.0"
}
]
Meta data looks like this:
"versions":{"required":true,"schema":
{"type":"array","items":"version","system":"versions"},"name":"Affects Version/s",....
Especially irritating and inconsistent is the fact that the very same field is exported by JIRA as <version>Version 2.0.0</version> in XML and for queries affectedVersion is to be used.
There are a few example of "edit issue" requests here.
You want to send a json that includes something like this:
{
"fields":
{
"versions":["1.0.0","1.1.0"],
"fixVersions":["2.0.0"]
}
}
In your code you use the key "versions" both for "Fix version(s)" and "Affected version(s)", which won't work. Also, you don't have to use additional "affectsVersion" or "fixVersion" keys.
You can also get more info about which fields you can edit and which values they allow using this REST call:
GET /rest/api/2/issue/{issueIdOrKey}/editmeta
Try it out for an issue you want to edit and it should put you on the right track. The output will also show that the "versions" key corresponds to the "Affected version(s)" field.
from jira import JIRA
auth_jira = JIRA('jira.your-oraganizsation.com', auth=('username', 'password'))
new_issue = auth_jira.create_issue(project='project_name', summary='jira_summary', description='jira_description', issuetype={'name': 'Defect'}, fields={'versions': [{'name': '1.0.0'}, {'name': '18.8.0'}] })

MongoDB: merge raw object into nested structure

I have an array object like this:
[
'things'=>[
't1'=>[ 'prop1'=>3 ]
]
]
and I want to merge it into the following collection entry:
[
'id'=>123,
'things'=>[
't1'=>[ 'prop1'=>1, 'prop2'=>2 ],
't2'=>[ 'prop1'=>1, 'prop2'=>2 ]
]
]
If I try to use the object as is, the following code deletes things.t1.prop2 and things.t2:
$db_collection->update([ 'id'=>123 ], [ '$set'=>[ 'things'=>[ 't1'=>[ 'prop1'=>3 ] ] ] ]);
Probably I have to convert the object into the dot notation format like this:
$db_collection->update([ 'id'=>123 ], [ '$set'=>[ 'things.t1.prop1'=>3 ] ]);
I can also read the whole entry first, merge data with a specific function inside my script, and write the updated entry back into the database.
But these ways don't seem to be very efficient. Is there a special command in Mongo to incorporate a raw object into nested data without overwriting the whole entry?
P.S.: I'm using a PHP MongoDB driver.

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.

Categories