I'm trying to convert an array in string in PHP so that I can store it into mySQL fields and reversely I can fetch:
Following is the data format:
array:2 [
0 => array:2 [
"year" => "234"
"amount" => "2387"
]
1 => array:2 [
"year" => "23"
"amount" => "324"
]
]
I'm trying something like this:
$var = implode(',', $data['revenues']);
I tried using implode but it is not working. Please help me out.
Edit
I tried this before:
public function store(Request $request)
{
$this->validate($request, Research::$create_validation_rules);
$data = $request->only(['coverage_date', 'company_id', 'contact_id', 'type', 'reco', 'target', 'projections', 'revenues', 'ebitas', 'profits']);
$data['coverage_date'] = Carbon::parse($request->coverage_date)->toDateTimeString();
$data['revenues'] = json_encode($data['revenues']);
$data['projections'] = json_encode($data['projections']);
$data['profits'] = json_encode($data['profits']);
$research = Research::create($data);
if($research)
{
return response()->json(['msg' => 'Successfully Created'], 200);
}
else
{
return response()->json(['msg' => 'Something went wrong'], 450);
}
}
Error which I'm getting is:
Use json_encode
example
$array = [["year" => "234","amount" => "2387"],["year" => "23","amount" => "324"]];
/*
Depending on PHP Version you can pass additional parameters
in json_encode for example json_encode($array,JSON_PRETTY_PRINT)
*/
$string = json_encode($array);
echo $string;
check this on PHP sandbox
Related
First Post, any help is appreciated.
I have a PHP file (Array) with data from a database, which i need to compare to a JSON file (Object).
By looking through forums i have seen stuff about jQuery and AJAX requests, so i was thinking maybe i need to use those for my solution.
The PHP Array
<?php
$codes = [
[
'code' => '1111',
'name' => 'Management',
],
[
'code' => '1305',
'name' => 'Price',
],
[
'code' => '1161',
'name' => 'Service',
]
and the array goes on.
The JSON Object
[{"name":"Management","code":"1111","accountingArea":"3194","managerUsername":null},
{"name":"Storage","code":"9033","accountingArea":"3194","managerUsername":null}]
is the way the JSON Object is formatted.
For some reason it has no name, which i don't know if it's a problem, when it comes to comparing two different files.
The product will need to be a PHP script that tells the user which entries are missing in the other file.
The only thing that needs to be compared are the codes.
I have not done anything with JSON files yet and am quite new to PHP too.
So far i have only included both the files in my script file and don't know where to start things off.
You can take JSON from file as string and use php json_decode() function that function will return a php array, then you can just make a foreach cicle and check the codes
Your code should be similar to this
<?php
$codes = [
[
'code' => '1111',
'name' => 'Management',
],
[
'code' => '1305',
'name' => 'Price',
],
[
'code' => '1161',
'name' => 'Service',
]];
$json_str = '[{"name":"Management","code":"1111","accountingArea":"3194","managerUsername":null},
{"name":"Management","code":"11141","accountingArea":"3194","managerUsername":null},
{"name":"Management","code":"1305","accountingArea":"3194","managerUsername":null},
{"name":"Management","code":"1161","accountingArea":"3194","managerUsername":null},
{"name":"Storage","code":"9033","accountingArea":"3194","managerUsername":null}]';
$json_array = json_decode($json_str, true);
$result = array();
$codesN = array_column($codes, 'code');
$i = 0;
for($i; $i < count($json_array); $i++) {
if(in_array($json_array[$i]["code"], $codesN)) {
$result[] = $json_array[$i]["code"];
}
}
var_dump($result);
This will return:
array(3) {
[0]=>
string(4) "1111"
[1]=>
string(4) "1305"
[2]=>
string(4) "1161"
}
Try this. See comments for step-by-step explanation.
Output:
array(2) {
[1]=>
string(4) "1305"
[2]=>
string(4) "1161"
}
Code:
<?php
// Your input array.
$codes = [
[
'code' => '1111',
'name' => 'Management',
],
[
'code' => '1305',
'name' => 'Price',
],
[
'code' => '1161',
'name' => 'Service',
]
];
// Your input JSON.
$json = '[{"name":"Management","code":"1111","accountingArea":"3194","managerUsername":null},{"name":"Storage","code":"9033","accountingArea":"3194","managerUsername":null}]';
// Get differences:
// Get values from $codes that are not present in $json.
// Switch the arguments to perform the inverse comparison.
$diff = array_diff(
array_column($codes, 'code'),
array_column(json_decode($json, TRUE), 'code')
);
var_dump($diff);
/*
Output:
array(2) {
[1]=>
string(4) "1305"
[2]=>
string(4) "1161"
}
*/
I am currently trying to learn Laravel and PHP in general.
I need to be able to import an Excel file, then get the data from that file. Currently, the import part works and I can see the data from the file. However, I am having trouble accessing the data.
I've read about the toArray() function in Laravel, and is using that as below:
$data = Excel::load($path, function($reader) {})->skipColumns(2)->get();
$data = $data->toArray();
foreach ($data as $key => $value) {
//We only need some of the available data.
echo $value->next_milestone_desc_cur._comp._incl_rltd;
echo $value->shipment_id;
}
Above code gives me below error:
Trying to get property 'next_milestone_desc_cur' of non-object
Below is an output from the array, which I have generated using dd($value):
array:543 [▼
0 => array:20 [▼
"next_milestone_desc_cur._comp._incl_rltd" => "005. DK - Add DropMode/Local Trp Org in Pickup Tab"
"milestone_cur._comp._sequence_no" => "005"
"cur._comp._export_validation" => "NOT OK"
"shipment_id" => "SBRY0162091"
"consol_id" => "CDK327188" ]
1 => array:20 [▼
"next_milestone_desc_cur._comp._incl_rltd" => "005. DK - Add DropMode/Local Trp Org in Pickup Tab"
"milestone_cur._comp._sequence_no" => "005"
"cur._comp._export_validation" => "NOT OK"
"shipment_id" => "SBRY0162124"
"consol_id" => "CDK327221"
]
What am I doing wrong here? I have also tried
echo $value[0]->next_milestone_desc_cur._comp._incl_rltd;, however this doesn't work either.
You are trying to access an array as an object hence your error and to address you second point, you need to use a nested loop to then access the sub-array.
Your array looks something like this:
$array = [
0 => [
0 => [
'test' => 'value'
],
1 => [
'test' => 'something'
]
],
1 => [
0 => [
'test' => 'value'
],
1 => [
'test' => 'something'
]
]
];
You need the following loop:
foreach ($array as $key => $nested) {
foreach ($nested as $nested_value) {
// You have access to your inner arrays.
echo $nested_value['test'] . ' | ';
}
}
Where your nested loops $nested would be $value.
Live Example
Repl
Your output from dd($value) shows that $value is an array. So you cannot use arrow notation that is for objects. Change these lines:
echo $value->next_milestone_desc_cur._comp._incl_rltd;
echo $value->shipment_id;
To:
echo $value[0]["next_milestone_desc_cur._comp._incl_rltd"];
echo $value[0]["shipment_id"];
I would need to insert an associative array into my existing code, to make an HTTP request.
My code at the moment:
$payload =[
'method_id' => 2,
'api_key' => 5,
];
$res = $client->post('some.website', [,
'form_params' => [
foreach($this->payload as $key => $s_key) {
$key => $s_key;
}
],
]);
How to make now sure, each element of the $payload array is inserted into the form_params array?
I tried using:
foreach ($this->payload as $s_key => $key) {
//?!
}
But I don't know how to proceed inside the form_params element?
Using the payload array directly inside form elements is resulting into this:
"form_params" => [
0 => array:2 [
"method_id" => 2
"api_key" => 5
]
]
What I would need is something like this:
"form_params" => [
"method_id" => 2
"api_key" => 5
]
You should just be able to just use the $payload variable directly, like so:
$res = $client->post('some.website', [
'form_params' => $payload,
]);
My question is a bit different to most like this, I basically want to do the opposite to this question from Haluk.
So I have a JSON string:
{
"main":
{
"title": "QuickPub",
"defaultRole": "BU"
},
"roles":
{
"TU":
{
"name": "testUser",
"code": "TU"
}
}
}
and I want to be able to generate a string containing a php array definition from it:
<?php
return [
"main" =>
[
"title" => "QuickPub",
"defaultRole" => "BU"
],
"roles" =>
[
"TU" =>
[
"name" => "testUser",
"code" => "TU"
]
]
];
?>
EDIT:
I have tried json_decode() but this produces a variable, I need a string that I can put in a php file that will reproduce this without using php_decode.
I think this will solve your problem. First of all convert your json string to an array using json_decode($string,1); then convert that array to string representation using print_r($array,1); this will return your result as array string representation.
For example:
$json='{}' // its a demo
$array= json_decode($json,1); // an array
$result = print_r($array,1);
echo $result;
This is an adaptation of Being Sunny's answer, but using the var_export() function rather than print_r.
As described here by phihad
var_export prints valid php code. Useful if you calculated some values and want the results as a constant in another script
the script:
$json = '{"main":{"title": "QuickPub","defaultRole": "BU"},"roles":{"TU":{"name": "testUser","code": "TU"}}}';
$array = json_decode($json, 1);
$result = var_export($array, 1);
echo $result;
produces:
array(
'main' => array(
'title' => 'QuickPub',
'defaultRole' => 'BU',
),
'roles' => array(
'TU' => array(
'name' => 'testUser',
'code' => 'TU',
),
),
)
This can be achieved using this code:
$output = 'return ' . rtrim(preg_replace(['/{/', '/}/', '/:/'], ['[', ']', ' =>'], $json)) . ';';
this replaces { with [, } with ], and : with =>, trims any whitespace from the end, appends a ; and prepends a return statement.
this produces the output requested in the question bar the open and closing php tags.
I have the following method:
$results = array_filter($arr['people'], function($people) use ($searchId) {
return in_array($searchId, $people['member']);
});
echo json_encode($results);
This returnes an array like this:
[{"id":"8080","content":"foo","member":[123,456],"interval":7}]
But if there more than one result it will return this:
["0": {"id":"8080","content":"foo","member":[123,456],"interval":7}]
["5": {"id":"8082","content":"bar","member":[1234,3456],"interval":5}]
I want to replace the "automatically" given ID with the ID which is in the Array - like this:
["8080": {"id":"8080","content":"foo","member":[123,456],"interval":7}]
["8082": {"id":"8082","content":"bar","member":[1234,3456],"interval":5}]
Have somebody an idea?
Try this one,
$arr = [
0 => [
"id" => 8082,
"content" => "test",
"interval" => "7",
],
5 => [
"id" => 8086,
"content" => "test",
"interval" => "7",
],
];
$ids = array_column($arr, "id");
$result = array_combine($ids, $arr);
print_r($result);
echo json_encode($result);
array_column which states Return the values from a single column in the input array.
array_combine which states Creates an array by using one array for keys and another for its values.
Try this simple way :
$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);