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'];
Related
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] );
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.
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.
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".
I am trying to use a jQuery gantt as a wordpress plugin. Currently I'm stuck on editing the data.json. I use a php form to populate a new item. When submitting the form, it will add data to the file, but behind the closing square brackets.
[{
...
},
{ "name" : "Vermessung"
, "desc" : ""
, "values": [
{ "id" : "5"
, "from" : "/Date(1363132800000)/"
, "to" : "/Date(1368655200000)/"
, "desc" : "Vom Beauftragen der Vermessung bis zur tatsächlichen Vermessung"
, "customClass": "ganttBlue"
, "label" : "Vermessung"
}
]
}
]
After submitting the form it looks like this:
[{
...
},
{ "name" : "Vermessung"
, "desc" : ""
, "values": [
{ "id" : "5"
, "from" : "/Date(1363132800000)/"
, "to" : "/Date(1368655200000)/"
, "desc" : "Vom Beauftragen der Vermessung bis zur tatsächlichen Vermessung"
, "customClass": "ganttBlue"
, "label" : "Vermessung"
}
]
}
]{"name":null,"desc":null,"values":{"id":null,"from":null,"to":null,"desc":null,"customClass":null,"label":null}}
This is the requested php Code which will adding stuff to the json:
$file = jQg_BASENAME_DIR.'/inc/data.json';
log_me('This is a message for debugging purposes');
if(isset($_POST['submit'])){
$json = file_get_contents( $file );
$data = json_decode($json);
// convert form data to json format
$postArray = array(
"name" => $_POST['name'],
"desc" => $_POST['desc'],
"values" => array(
"id" => $_POST["value_id"],
"from" => $_POST['value_from'],
"to" => $_POST['value_to'],
"desc" => $_POST['value_desc'],
"customClass" => $_POST['value_class'],
"label" => $_POST['value_label']
)
); //you might need to process any other post fields you have..
$json = json_encode( $postArray );
array_push($json, $postArray);
// write to file
file_put_contents( $file, $json, FILE_APPEND);
I also can't establish the square bracket after value. How can I fix this?
As I said in my comment
$json = file_get_contents( $file );
// $json is now a string
$data = json_decode($json);
// $data is a PHP object
// So lets call the second array $data->someArray
// since I do not know what it is called looking at your file
// convert form data to PHP array format
$postArray = array(
"name" => $_POST['name'],
"desc" => $_POST['desc'],
"values" => array(
"id" => $_POST["value_id"],
"from" => $_POST['value_from'],
"to" => $_POST['value_to'],
"desc" => $_POST['value_desc'],
"customClass" => $_POST['value_class'],
"label" => $_POST['value_label']
)
); //you might need to process any other post fields you have..
// $postArray is a PHP object
// $json = json_encode( $postArray ); // do NOT convert here
array_push($data->someArray, $postArray);
$json = json_encode($data);
// write to file
file_put_contents( $file, $json, FILE_APPEND);
Your values field is an array of objects instead of an object (the encoding of a php associative array is a json oject). So for values to have square brackets instead of "values" => array() you would need "values" => array( array("id" => ... etc. ) )
As for your first problem you've inverted the json_encoding. First push your postArray into data, then json_encode data.