Getting data in particular format in PHP for Post request - php

I have to send some data in the below format-
$postData = [
'certExpiryDate' => $certExpiryDate,
'certType' => 'SSL',
'AltName' => [
$altName[0],$altName[1]
],
'csr' => $csr
];
$altName is an array that has 2 or more strings like- domain1.com, domain2.com.
The AltName parameter expects the data in this format-
'AltName' => [
'domain1.com','domain2.com'
],
(if I hardcode and send it like this, everything works fine.. this is the correct format)
If I take the array $altName directly like this-
'AltName' => [
$altName
],
I did a var_dump and for this it adds quotes outside like- "domain1.com, domain2.com", which it considers wrong.
I need it to be in the format of $altName[0],$altName[1] which would be correct, but I'm struggling on how to loop through this array in case it has more values than 2 and still get it in the required format.

Your attempt:
'AltName' => [
$altName
],
doesn't work as intended because it wraps the array $altName inside another array (created by the [ and ]).
Just set the $altName array to be the value of the property directly. There's no need for an extra array:
'AltName' => $altName
Demo: http://sandbox.onlinephpfunctions.com/code/fa3dd6a974be7ced4bdc5d878f692549b96e2b95

but I'm struggling on how to loop through this array in case it has
more values than 2 and still get it in the required format.
posting direct values:
//$altName = ["domain1.com", "domain2.com"];
//OR
$altName = array("domain1.com", "domain2.com");
$postData = ['AltName' => $altName];
var_dump($postData);
output:
array(1) {
["AltName"]=>
array(2) {
[0]=>
string(11) "domain1.com"
[1]=>
string(11) "domain2.com"
}
}

Related

Comparing a JSON file and a PHP file

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"
}
*/

Correctly format JSON file

I'm trying to create a JSON file which contains objects and an array. Yet I'm missing the [ ]-brackets. I don't really know the exact terms for these JSON parts, which makes finding a solution using Google incredibly hard. I'm also a fairly new PHP coder, so I'm still learning. Any help or tips are really appreciated!
Code to create the JSON file:
$db_export = [
'account' => [
'username' => $username,
'email' => $email
]
];
file_put_contents("output.json", json_encode($db_export, JSON_PRETTY_PRINT));
Which outputs as:
{
"account": {
"username": "test",
"email": "test#domain.com"
}
}
What it's supposed to be:
{
"account": [
{
"username": "test",
"email": "test#domain.com"
}
]
}
Adding [] characters will help. This creates an array inside the array.
$db_export = [
'account' => [[ // <--- Added
'username' => $username,
'email' => $email
]] // <--- Added
];
file_put_contents("output.json", json_encode($db_export, JSON_PRETTY_PRINT));
This is how you get the result you want.
Output :
{ "account": [ { "username": null, "email": null } ] }
I guess it was a little simple :)
I am adding this to explain what is going on with the original answer. You can find this same information in the json_encode php manual page, in the example sections.
With any simple PHP array, json_encode will transform the PHP array into a JSON array:
$simple = array('apple', 'banana', 'coconut');
echo json_encode($simple);
Returns:
["apple","banana","coconut"]
Any associative array will be turned into a json object {} and each associative key will become a property name.
$associative = array('breakfast' => 'apple', 'lunch' => 'banana', 'dinner' => 'coconut');
echo json_encode($associative);
Returns:
{"breakfast":"apple","lunch":"banana","dinner":"coconut"}
In your example, you have an array with an associative key 'account' that contains an array with 2 child elements, each with an associative key.
This is the reason json_encode() is turning your structure into json objects.
In #Smokie's answer, the addition of an extra parent array that is "simple" ie. not keyed with a name, causes json_encode (following it's simple transformation rules) to create a javascript array, which it then sticks the javascript object inside of.
$username = 'test user';
$email = 'foo#bar.com';
$db_export = [
'account' => [[ // <--- Added
'username' => $username,
'email' => $email
]] // <--- Added
];
var_dump($db_export);
Returns:
array(1) {
["account"]=>
array(1) {
[0]=>
array(2) {
["username"]=>
string(9) "test user"
["email"]=>
string(11) "foo#bar.com"
}
}
}
Here I use var_dump as a quick debugging tool to show what the PHP array looks like. The important thing to note is that 'account' is now an array(1) with one element ( the 0th element) that contains your original child array.
Presumably you need this because the assumption is that an account could have multiple accountname/email address pairs. If that isn't the case, I would question why you need to force a useless array. I personally don't see how an 'account' could have multiple username/email pairs associated with it.
With that said, this code should further illustrate how this all works, and why:
$username = 'test user';
$email = 'foo#bar.com';
$db_export = [
'account' => [[ // <--- Added
'username' => $username,
'email' => $email
]] // <--- Added
];
//Add another username/email pair to account
$db_export['account'][] = ['username' => 'test2 user', 'email' => 'test2#bar.com'];
echo json_encode($db_export, JSON_PRETTY_PRINT);
Returns:
{
"account": [
{
"username": "test user",
"email": "foo#bar.com"
},
{
"username": "test2 user",
"email": "test2#bar.com"
}
]
}

PHP - MongoDB: Retrieve Fields from Sub Document with Field Names in Array

Consider an Array
$lettersArray = [A,C,E,G]
and my MongoDB Collection has the following structure.
{
Collection : {
letters:{
A:{...},
B:{...},
...
Z:{...}
}
}
}
Consider that the Letter Sub document is a part of a larger collection. Hence I am using Aggregation.
Right Now I have tried to project -
['$Collection.letters' => ['$elemMatch' => ['$in' => $lettersArray]]
and also tried
['Letters' => ['$in' => [$lettersArray,'$Collection.letters']]
But it didn't work.
In the End, I want result like the following:
[
Collection => [
letters => [
A => [...],
C => [...],
E => [...],
G => [...]
]
]
]
Is there any way to do this?
In PHP you can use array_combine with array_fill to create the empty arrays.
$lettersArray = ['A','C','E','G'];
$letters = array_combine($lettersArray, array_fill(0,count($lettersArray), []));
Array_fill creates an array from index 0, to the count of items in $lettersArray with the contents []
Output:
array(4) {
["A"]=>
array(0) {
}
["C"]=>
array(0) {
}
["E"]=>
array(0) {
}
["G"]=>
array(0) {
}
}
https://3v4l.org/TeoFv
I think you are mistaken in the way you are trying to access the documents' information.
If you take a look at your MongoDB document, you will see that it is in fact not an array, so you should not use $elemMatch to project these fields, but simple projections. In your case, you should project in this way:
[
'$project' => [
'Collection.letters.A' => 1,
'Collection.letters.C' => 1,
'Collection.letters.E' => 1,
'Collection.letters.G' => 1
]
]
By the way, you don't need to use the aggregation framework to compute such a projection. You could just use find(), and use the projection in the options, which are the functions' second argument:
myCollection->find(query, [
'projection' => [
'Collection.letters.A' => 1,
'Collection.letters.C' => 1,
'Collection.letters.E' => 1,
'Collection.letters.G' => 1
]
]);
Cheers,
Charles

Laravel How can I return array of objects

I've got simple array of objects:
"myObject" => [
'key1' => ["property1" => 'value1', "property2" => 'value2'],
'key2' => ["property1" => 'value1', "property2" => 'value2'],
...
],
When I'm returning this via laravel dot syntax:
return [
'listOfObjects' => trans(objects)
]
I've got:
myObject: {
key1: {property1:'value1', property2:'value2'},
key2: {property1:'value1', property2:'value2'},
etc..
}
It's simple.
Now how can I modify my return to get only an array of objects, without numbers:
myObject: {
{property1:'value1', property2:'value2'},
{property1:'value1', property2:'value2'},
etc..
}
Any ideas?
I don't think it is possible to solve in PHP. As it is said in the manual
"...index may be of type string or integer. When index is omitted, an
integer index is automatically generated, starting at 0..."
Also, what you are asking seems to be quite pointless. If you could describe what it is you are trying to accomplish, people might be able to help you better.
The function to use in this case is:
$tryit = trans('objects');
$new = collect($tryit)->flatten(1);
$new->values()->all();
unfortunatelly there is a bug in Laravel 5.6 on this function and it digs two level deep instead of one :/
[edit]
I think I now understand what you want. What you call an Array in PHP is not necessarily an Array in JSON. For JSON your "myObject" is an Object.
For JSON to recognize something as an Array, it can only have numbers as keys.
So change the keys from "key1", "key2", ... into 0, 1, ...
$result = [];
foreach($myObject as $element){
$result[] = $element;
}
return $result;
After that, $result looks like this
$result = [
0 => ["prop1" => "val1", "prop2" => "val2"],
1 => ["prop1" => "val1", "prop2" => "val2"]
]
Or equivalently in the short notation
$result = [
["prop1" => "val1", "prop2" => "val2"],
["prop1" => "val1", "prop2" => "val2"]
]
Now JSON should recognize this as an Array instead of an Object when Laravel converts $result to JSON or you make it yourself: return response()->json($result);
[previous:]
You can not return an object which has values but no keys.
The simplest form of keys are numbers, which is what arrays are using.

How to replace nested array value inside the Laravel request using merge?

There is a function to replace the input from the request which is called merge.
I would like to change a value of a nested array so that it can be validated by $this->validate method..
This is the output of $request->all()
array:2 [
"type" => "customer"
"users" => array:1 [
0 => array:3 [
"name" => "eeee"
"username" => "eeee"
"password" => "123456"
]
]
]
How do I access the username value and change it, provided I use a forloop
for($i=0; $i < count($request->users); $i++){
// i need to access the value here
// i have done something like $request->merge(['users'][$index]['username'] => 'xxx');
// it doesnt work
}
Any solution guys?
Thank you.
You can try something like this using merge method:
$new_users_data = $request->input('users');
foreach ($new_user_data as &$user_data) {
$user_data['username'] = 'new name';
}
$request->merge([
'users' => $new_users_data,
]);
You can also replace whole input with new one with request replace method.

Categories