Convert multiple input value to json array on Php? - php

I'm trying to convert multiple input values to json array using php.
Form:
<input name="title[]">
<input name="description[]">
<input name="total[]">
What i'm trying to get:
{"results":
[{"title", "description", "total" }],
[{"title", "description", "total" }],
[{"title", "description", "total" }],
[{"title", "description", "total" }]
}
Php Code:
$itemCount = count($_POST["title"]);
$_POST['results'] = [];
for($i=0;$i<$itemCount;$i++) {
if(!empty($_POST["title"][$i]) || !empty($_POST["description"][$i]) || !empty($_POST["total"][$i])) {
$_POST['results'] = json_encode([
[
'title' => cleardata($_POST["title"][$i]),
'description' => cleardata($_POST['description'][$i]),
'total' => cleardata($_POST['total'][$i])
],
]);
}
}
print_r(json_encode($_POST['results']));

Your form isn’t clear. I’ll assume it is a set of inputs, each title matching with exactly one description and exactly one total fields.
Also, the JSON you expect is not valid.
We’re making new arrays with elements with the same index in each posted array. You can eventually cast them to Object. We combine them in a global array and parse it to JSON thanks to json_encode().
// Since you didn’t indicate form method
$titleData = $_POST['title'] ?? $_GET['title'];
$descriptionData = $_POST['description'] ?? $_GET['description'];
$totalData = $_POST['total'] ?? $_GET['total'];
$results = [];
foreach ($titleData as $count => $result) {
$results[] = [$result, $descriptionData[$count], $totalData[$count]];
// You may cast the added array with (object) if you expect an object
// rather than an array.
}
return json_encode( ["results" => $results] );

Related

PHP - Find an object by key in an array of objects, update its value

I have an array of objects, and want to update an attribute of one of the objects.
$objs = [
['value' => 2, 'key' => 'a'],
['value' => 3, 'key' => 'b'] ,
];
Let's say I want to set the 'value' of the object with 'key'=>'a' to 5.
Aside from iterating over the array searching for the key, is there any quicker/efficient way of doing this?
Thanks.
EDIT: There is debate as to why I can't use an associative array. It is because this array is obtained from a JSON value.
If my JSON object is this:
"obj": {
"a": {
"key": "a",
"value": 2
},
"b": {
"key": "b",
"value": 3
}
}
There is no guarantee that the order of the objects will be retained, which is required.
Hence I need an index in each object to be able to sort it using usort(). So my JSON needs to be:
"obj": {
"a": {
"key": "a",
"value": 2,
"index": 1
},
"b": {
"key": "b",
"value": 3,
"index": 2
}
}
But I cannot use usort() on an object, only on arrays. So my JSON needs to be
"obj": [
{
"key": "a",
"value": 2,
"index": 1
}, {
"key": "b",
"value": 3,
"index":2
}
]
Which brings us to the original question.
By using array_column(), you can pull all the values with the index key in the arrays. Then you can find the first occurrence of the value a by using array_search(). This will only return the first index where it finds a value. Then you can simply replace that value, as you now have the index of that value.
$keys = array_column($objs, 'key');
$index = array_search('a', $keys);
if ($index !== false) {
$objs[$index]['value'] = 5;
}
See this live demo.
http://php.net/array_search
http://php.net/array_column
You can make the array associative with array column. That way you can directly assign the value.
$objs = [ ['value'=>2, 'key'=>'a'], ['value'=>3, 'key'=>'b'] ];
$objs = array_column($objs, null, "key");
$objs['a']['value'] = 5;
https://3v4l.org/7tJl0
I want to recommend you reorginize your array lake that:
$objs = [
'a' => ['value'=>2, 'key'=>'a'],
'b' => ['value'=>3, 'key'=>'b']
];
And now
if( array_key_exists( 'a', $objs )) {
$objs ['a'] ['value'] = 5;
}
I had it like that initially. But I need for the objects to have an
index value in them, so I can run usort() on the main array. This is
because the array comes from JSON where the original order isn't
respected
Then create an index array:
// When fill `$objs` array
$objs = [];
$arrIndex = [];
$idx = 0;
foreach( $json as $item ) {
$arrIndex [ $item ['key']] = $idx;
$objs [$idx ++] = $item;
}
// And your task:
if( array_key_exists( 'a', $arrIndex )) {
$objs [ $arrIndex ['a']] ['value'] = 5;
}
Aside from iterating over the array searching for the key, is there
any quicker/efficient way of doing this?
You have to pay the price of iteration either way.
You can search your collection for the interesting object (takes linear time), or you form some kind of dictionary data structure, e.g. hash table (takes linear time) and then find the interesting object in constant time.
No free lunches here.

Check POST Data - JSON Array

I´m trying to check the data of my JSON file. It works for strings in the json file, but how to handle it with arrays in the array?
What i send:
{
"info" : "test",
"data" : [
{
"startdate": "2018-01-01T10:00:00+0100",
"enddate": "2018-01-01T17:00:00+0100"
}
]
}
What i´ve yet:
$dataReq = array(
'info' => $request->get('info'),
'date' => $request->get('date'), // my array
);
foreach ($dataReq as $a => $value) {
if(empty($value)) {
return new View('The field \''.$a.'\' is required!');
}
}
But the function empty doenst work for arrays so far. It will return false, cause the array is there. How can i check the "startdate" key?
btw: i´m using symfony3(FOSRestBundle), php 7.0
You can check if the value is an array and filter null values from it, then test if it's empty.
$dataReq = array(
'info' => $request->get('info'),
'data' => $request->get('data'), // my array
);
foreach ($dataReq as $a => $value) {
if(is_array($value)) $value = array_filter($value);
if(empty($value)) {
return new View('The field \''.$a.'\' is required!');
}
}
array_filter() function's default behavior is to remove from array all values equal to null, 0, '' or false if no callback is passed.
Note: I assume you wanted to retrieve data and not date.
As commented by LBA, I also suggest to check the Symfony Validation component to deal with that instead.

get mongoDB embedded document array value using php?

How to get the contact values?, and How are the values stored in php?
{
_id : "001",
name : "fakename",
contact_address : {
street : "12 Street",
city : "Cosmos",
contact : [
"123456789",
"012345678"
]
}
}
Query :
$cursor = $collection->find ( array('name' => 'fakename' ), array( 'contact_address.contact' ) );
foreach ( $cursor as $doc ) {
echo $doc[ 'contact_address' ][ 'contact' ];
}
Result :
Array
Motive : Intend to print the contact values.
To print array values you can use print_r, var_dump or var_export - for debugging purposes.
To iterate them and use values in other places - you can use for example foreach like that:
foreach ($array as $key => $value) {
// $key holds the index, $value holds the value of the array
}
There are other ways to iterate array, in fact way too many in PHP, but this should suffice.

Parse JSON with PHP: Syntax complication

I'm getting the following errors:
Notice: Undefined index: value in C:\fileSystemLocation/phpFile.php on line 43
Notice: Undefined index: value in C:\fileSystemLocation/phpFile.php on line 44
when I'm trying to parse the following json data:
"data":[
"phone":[
{"value":"",
"primary":true
}],
"email":[
{"value":"",
"primary":true
}]
]
With the following statements
$response = json_decode($json_response, 1);
// Gets the count of records returned from the api. Used in the for loop to go through response 1 array element at a time.
$count = Count($response['data']);
//create array of the json data we want to export to csv
for ($x=0; $x<$count; $x++)
{
$jsonDataInArray[] = array
(
"phone" => $response['data'][$x]['phone']['value'],
"email" => $response['data'][$x]['email']['value'],
)
}
What is wrong with the syntax of the above 2 statements? I'm wondering if there is any error with my syntax above specifically with "phone" => $response['data'][$x]['phone']['value'],
"email" => $response['data'][$x]['email']['value'],
Looks like your JSON data is missing {} (malformed) and, also, you're using a phone key (alphabetical) on a numerical key array ([]). To use alphabetical keys you have to have a dictionary ({}, key-value arrays). Looks like your JSON should be like this:
{
"data" :
[
{
"phone" :
{
"value" : "",
"primary" : true
},
"email" :
{
"value" : "",
"primary" : true
}
}
]
}
Also remember that the function to count items in an array is count(), not Count() (capitalization matters).
I would do this then:
$jsonDataInArray = array();
$response = json_decode( $json_response, TRUE );
$data = $response['data'];
$count = count( $data );
foreach ( $data AS $index => $object )
{
$values = array(
"phone" => $data[$index]['phone']['value'],
"email" => $data[$index]['email']['value']
);
array_push( $jsonDataInArray, $values );
}
Here's the syntax that worked for me:
"phone" => $response['data'][$x]['phone'][0]['value'],
"email" => $response['data'][$x]['email'][0]['value']
The ending objects in the json data looked like (WARNING: not the whole string of json data, just the end):
"phone":[{"value":"","primary":true}],"email":[{"value":"","primary":true}]
and since there are arrays, I have to include the [0]
The following code:
"phone" => $response['data'][$x]['phone']['value'],
"email" => $response['data'][$x]['email']['value']
Would work with these ending json data objects (WARNING: not the whole string of json data, just the end):
"phone":{"value":"","primary":true},"email":{"value":"","primary":true}
Your syntax inside your loop is wrong. Change:
"email" => $response['data'][$x]['email']['value'],
To:
$email = $response['data'][$x]['email']['value'];

How to replace an element in an array

I have a COLLECTION collflokks in MongoDB, sample Document is :-
{
"_id" : "b_8AUL",
"f_name" : "Pizza. Hut",
"f_lat" : "22.7523513",
"f_lng" : "75.9225847",
"c_uid" : "33",
"f_type" : NumberLong(3),
"members" : [
"42",
"43"
]
}
Within the "members" array , I want to add Arrays like {id:42,name:Mark} , {id:43,name:Hughes}
Currently i'm adding just ids(eg.42,43). I'm only concerned about the new data as it will have new ids .Please suggest.
Earlier I was using this code to push into the members Array:
$flokkCollection = 'collFlokks';
$flokkCollection->update(
array("_id" => $f_handle),
array('$push' => array("members" => $u_id))
);
Well if what you are asking here is "replacing your existing data" then you need to "loop" the results from the collection and "replace" the array content that exists with your new format.
There are likely smarter ways to approach this, but you are not really giving us all the required information in your question, so I can only answer in the basic terms.
Presuming you have:
$required = array(
array(array("id" => "42"), array("name" => "Mark")),
array(array("id" => "43"), array("name" => "Hughes"))
);
As input, then you do something like this:
function myMapper($v) {
return $v["id"];
}
$mapped = array_map("myMapper",$required);
foreach( $mapped as $value) {
$filtered = array_values(
array_filter($required,function($k) {
return $k["id"] == $value;
})
)[0];
collection.update(array(
array("members" => $value),
array('$set' => array(
"members.$" => $filtered
))
));
}
Which should use the positional $ operator to find the matched "position" of the array element by the value used in the "query" portion of the update statement, then in the "update" portion of that statement $set that current array index to the new value at the "filtered" content index from the original input array.
Outside of PHP. We call these inner elements "objects" and not "arrays" which is a PHP notation trait. Key/value things are "objects" and "lists" are "arrays".

Categories