Create JSON object with multiple values inside an array in PHP - php

I am working with Acuity Scheduling API and in order to post a custom field, I need to have a JSON object inside of the array that has 2 key/pair values, id and value. Here is my current code for this:
$postarray = array (
'datetime'=>'2017-02-01T14:00:00-0800',
'appointmentTypeID'=>'Appt ID',
'firstName'=>'First Name',
'lastName'=>'last Name',
'email'=>'myemail',
'phone'=>'phone #',
'fields' => array(
array('id'=>'1234', 'value'=>'Field Data')
)
);
$post = json_encode($postarray);
I have an array inside of the 'fields' array because I don't know how to add a json object with 2 values inside of an array that will then go through json_encode, as the request requires that it be converted to JSON first before being sent.
It is currently giving me this error: "{"status_code":400,"message":"The intake form field \u00221234\u0022 does not exist on this appointment." Where after "u0022" it adds on my field id. What I need is for my main array to become a JSON Object, the 'fields' to be an array, then the individual id and value pairs to be their own objects, like so (Taken Directly from Acuity Scheduling API):
{
"datetime": "2016-02-03T14:00:00-0800",
"appointmentTypeID": 1,
"firstName": "Bob",
"lastName": "McTest",
"email": "bob.mctest#example.com",
"certificate": "ABC123",
"fields": [
{"id": 1, "value": "Party time!"}
]
}
Here is Acuity Scheduling API for reference on this particular request, https://developers.acuityscheduling.com/reference#post-appointments

'fields' => array(
json_encode(array('id'=>'1234', 'value'=>'Field Data'))
)

The ID should be a number, not a string, so don't put it in quotes.
$postarray = array (
'datetime'=>'2017-02-01T14:00:00-0800',
'appointmentTypeID'=>'Appt ID',
'firstName'=>'First Name',
'lastName'=>'last Name',
'email'=>'myemail',
'phone'=>'phone #',
'fields' => array(
array('id'=> 1234, 'value'=>'Field Data')
)
);
If you're getting the ID from a script parameter, use intval() to convert it from a string to a number.

Related

Detect if array of objects within an object has duplicate names

I'm looking for a smart way to find out if my array of objects within an object has multiple name values or not to do a validation since it's only allowed to have one array name per inner array:
$elements = [];
$elements[18][20] = [
[
'name' => 'Color',
'value' => 'Red'
],
[
'name' => 'Color',
'value' => 'Green'
],
[
'name' => 'Size',
'value' => 'S'
]
];
$elements[18][21] = [
[
'name' => 'Size',
'value' => 'S'
],
[
'name' => 'Length',
'value' => '20'
],
];
error_log( print_r( $elements, true ) );
So the object 20 for example is invalid because it has 2 colors with the same value. At the end I was hoping to get a result array containing 1 duplicate name. This way I can output them like: "You have at least one duplicate name: Color".
My first idea was to loop over the array and do a second loop. This way it was possible to receive the inner arrays containing the stuff. Now I was able to add every name to another array. After this I was able to use count() and array_intersect() to receive a value of x which showed me if there are duplicates or not.
Now I had a count, but not the actual value to display. Before I use a semi-good solution, I was hoping to get any ideas here how I can make it better!
This loop will generate your expected output:
foreach($elements[18] as $index => $element){
//Get all the elements' names
$column_key = array_column($element, 'name');
//Get the count of all keys in the array
$counted_values = array_count_values($column_key);
//Check if count is > 1
$filtered_array = array_filter($counted_values, fn($i) => $i > 1);
//If the filter is not empty, show the error
if(!empty($filtered_array)){
//get the key name
$repeated_key = array_key_first($filtered_array);
echo "You have at least one duplicate name: {$repeated_key} at index {$index}";
break;
}
}
It relies in the array_count_values function.

Trying to add an array to an associated array

I have an associated array saved in my database that Im saving to a variable called response_cost using the Wordpress function get_post_meta.
$response_cost = get_post_meta( $postID, $metaKey, true );
The array looks something like this:
a:2: {
i:0;a:3:
{s:4:"type";s:6:"months";s:4:"cost";s:0:"";s:8:"modifier";s:1:"=";}
i:1;a:3:
{s:4:"type";s:5:"weeks";s:4:"cost";s:0:"";s:8:"modifier";s:1:"+";}
}
I have a form that I've created which outputs a new array and it's saved in a variable called $add_to_response_cost.
$add_to_response_cost = array (
'type' => $type,
'cost' => $cost,
'modifyer' => $modifyer
);
I'm can't figure out how to add $add_to_response_cost as another instance of $response_cost so that the out put ends up like so:
a:3: {
i:0;a:3:
{s:4:"type";s:6:"months";s:4:"cost";s:0:"";s:8:"modifier";s:1:"=";}
i:1;a:3:
{s:4:"type";s:5:"weeks";s:4:"cost";s:0:"";s:8:"modifier";s:1:"+";}
i:2;a:3:
{ my new array I've constructed via $add_to_response_cost }
}
Any help or direction with this is greatly appreciated.
To understand the problem, first we need to explain a little about how saving arrays in custom fields works
Here we have an array
$array = array(
"0" => array(
"type" => "months",
"cost" => null,
"modifier" => "=",
),
"1" => array(
"type" => "weeks",
"cost" => null,
"modifier" => "+",
)
);
If we decide to save it as a custom field in the database, we use the update_post_meta() function
update_post_meta( 1, 'response_cost', $array );
Before saving it to the database, Wordpress will serialize our array and then put it into the database.
As a result, the array will be saved in the database in the following format
a:2:{i:0;a:3:{s:4:"type";s:6:"months";s:4:"cost";N;s:8:"modifier";s:1:"=";}i:1;a:3:{s:4:"type";s:5:"weeks";s:4:"cost";N;s:8:"modifier";s:1:"+";}}
Then, if we want to get an array, we use get_post_meta()
$myarray = get_post_meta(1, "response_cost", true);
Wordpress will take a serialized array from the database and convert it to a typical array.
Then we can add any data we want to the array and save it back to the database.
$add_to_response_cost = array (
'type' => $type,
'cost' => $cost,
'modifyer' => $modifyer
);
$myarray[] = $add_to_response_cost;
update_post_meta( 1, 'response_cost', $myarray );
Usually this problem occurs when using the get_post_meta function without specifying a key, with only one parameter (ID), then we get arrays without processing and they must first be unserialized
This can also happen when you get an array from a database not through a Wordpress function, but by direct SQL query to the database.
Then you need to unserialize the array first, add data to it and pack it back.
You can try unserialize() to convert it to array.
$result = unserialize($response_cost);
Print_r($result);

How to get the values of a multi-dimensional array by key in Laravel?

Let's say for example you have a constant multi-dimensional array with multiple keys (and values), but you want to filter out specific keys with it's values. See a example array below:
const defaultInvestmentFields = [
[
'type' => 'system',
'investment_name' => 'Ballast'
],
[
'type' => 'system',
'investment_name' => 'Inverters'
],
[
'type' => 'system',
'investment_name' => 'Extra garantie inverters'
]
];
The output I want is an array with only the values of investment_name. Like ['Ballast', 'Inverters', 'Extra garantie inverters'].
Additionally to #Levi's answer, you can use an array helper to avoid having to transform the array into a collection and back: Arr::pluck()
Arr::pluck(Project::defaultInvestmentFields, 'investment_name');
A quick and neat solution would be to use the collect wrapper function which is provided by Laravel. After that we can use the pluck function in order to specify which values by their key(s) we want to get. For example:
collect(Project::defaultInvestmentFields)->pluck('investment_name');
Now we have a Collection of the following values: Ballast, Inverters and Extra garantie inverters.
In order to use it as an array, simply call toArray() on it.

Changing the in-place value of array with PHP

I want to modify a value inside JSON. Let's say I have this example JSON and I want to have the php change the phone number:
$data = '{
"firstName": "John",
"lastName": "Smith",
"age": 27,
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
}
]
}'
It sounds like I have to convert to an array using json decode:
$data = json_decode($data,true);
Which gives me this:
array (
'firstName' => 'John',
'lastName' => 'Smith',
'age' => 27,
'phoneNumbers' =>
array (
0 =>
array (
'type' => 'home',
'number' => '212 555-1234',
),
),
)
How do I then insert my own variable value into the array please? From my googling it looks like I might be on the right path with something along these lines:
$number = '50';
$data[$key]['age'] = $number;
What it does though, is just add it onto the end of the array, instead of correcting the value in place of the array file.
Firstly, you need to convert your json to PHP array usign json_decode function. check below code for updating/inserting keys:
$data['age'] = $number; // to update age
$data['newkey'] = 'newvalue'; //it will add key as sibling of firstname, last name and further
$data['phoneNumbers'][0]['number'] = '222 5555 4444'; //it will change value from 212 555-1234 to 222 5555 4444.
You just need to consider array format. If key exists then you can update value else it will be new key in array. Hope it helps you.

Pass array to javascript as array not JSON from PHP

First this is not a duplicate questions. I've looked through some similar problem and most of the answer is what I am using right now.
Here is the problem set up,
on PHP side
$array = array('name' => 'a', 'data' => array('0'=>15,'0.25'=>'18','0.35'=>19,'1' =>20));
echo json_encode($array);
on the JS side
data = $.parseJSON(data); // data is the return from the php script
above
As you can see the $array['data'] is an associative array with numeric number as its key and sorted in order. While parsing into JSON, javascript altered the order of that array and sorted 0 and 1 as numeric key and put them to the head of the object.
I know this is standard behavior for certain browser such as chrome, and IE9.
I've read somewhere that people suggest stick with array strictly if I want to maintain the order of the array.
But my question is how do you feed back an array from PHP to javascript as an array instead of using json object? Or is there other solution to this kind of problem . Thanks for the input in advance.
Thanks for the input in advance
Use an array to maintain order, and then an object to create the map. There are two ways. I would suggest:
$array = array('name' => 'a', 'data' =>
array(
array('key' => 0, 'value' => 15),
array('key' => 0.25, 'value' => 18),
array('key' => 0.35, 'value' => 19),
array('key' => 1, 'value' => 20),
)
);
echo json_encode($array);
Which will give you the JSON:
{
"name": "a",
"data": [
{"key": 0, "value": 15},
{"key": 0.25, "value": 18},
{"key": 0.35, "value": 19},
{"key": 1, "value": 20}
]
}
Then you will have order but to look up a certain key will be more difficult. If you want that to be easy you can return a mapping object as well like this:
$array = array('name' => 'a', 'data' =>
array(
"0" => 15,
"0.25" => 18,
"0.35" => 19,
"1" => 20,
),
'order' => array("0", "0.25", "0.35", "1")
);
echo json_encode($array);
Which will give you:
{
"name": "a",
"data": {
"0": 15,
"0.25": 18,
"0.35": 19,
"1": 20
},
"order": ["0", "0.25", "0.35", "1"]
}
One of these two methods of returning your data should prove to be the most useful for your specific use case.
Actually, it's PHP that takes the "0" and "1" keys and makes them numeric keys. This has nothing to do with your JavaScript.
There isn't any real way to work around this, but ideally your code should not rely on such things as "what order the keys of an object are in". It may be a better idea, just from what I see here, to separate the data into an array of keys and an array of values, then zip them back together on the JS side.
I'd suggest another field for storing order.
$array = array('name' => 'a',
'data' => array('0'=>15,'0.25'=>'18','0.35'=>19,'1' =>20),
'order'=> '0,0.25,0.35,1'
);
echo json_encode($array);

Categories