Need Proper JSON - php

I need to show data in Attribute and Value form but data is getting is in direct form.
I am trying this
Getting Data in this FOrm
{"FirstName":"sbncf","EmailAddress":"jscn#jnsc.cs","LastName":"jj","Phone":"653736","SearchBy":"jhjnjn"}
But i need in this Form
$data_string = '[{"Attribute":"FirstName","Value":"Bret"},{"Attribute":"LastName","Value":"Lee"},{"Attribute":"EmailAddress","Value":"bret.lee#australia.com"},{"Attribute":"Phone","Value":"8888888888"},{"Attribute":"SearchBy","Value":"Phone"}]';
I am using AJAx and using this
$data_string = json_decode(json_encode($_POST));
enter image description here

You need to store data into an another array, new array must contains Attribute and Value indexes, something like this example:
// testing $_POST data
$post = array();
$post['FirstName'] = 'sbncf';
$post['EmailAddress'] = 'jscn#jnsc.cs';
$post['LastName'] = 'jj';
$newArray = array(); // initialize new array
$i = 0;
foreach ($post as $key => $value) {
$newArray[$i]['Attribute'] = $key;
$newArray[$i]['Value'] = $value;
$i++;
}
//use json_encode here:
$data_string = json_encode($newArray);
echo $data_string;
Result:
[{"Attribute":"FirstName","Value":"sbncf"},{"Attribute":"EmailAddress","Value":"jscn#jnsc.cs"},{"Attribute":"LastName","Value":"jj"}]

Related

How to show all index data from Codeigniter and mongodb?

I have the code to show TripUUID. But it showed just one data. The code is as follows:
function list_of_tripreview(){
$data = $this->data;
$arr = [];
$data['list_of_tripreview'] = $this->cms_model->list_of_tripreview();
$TripUUID = $data['list_of_tripreview'][0]['TripUUID'];
echo json_encode($TripUUID);
This code gives the output TripUUID on index 0. How do I revise this program to show all index data without [0]?
You can use foreach loop
$data['list_of_tripreview'] = $this->cms_model->list_of_tripreview();
$datas = $data['list_of_tripreview'];
//$TripUUID = $data['list_of_tripreview'][0]['TripUUID'];
foreach($datas as $key => $item){
echo $item['TripUUID'].'<br>';
}

Create JSON response from Parsed XML PHP

I am parsing thorugh a eBay API response. I want to deliver this back to a website cleaner and easier to parse with JavaScript. I successfuly Parsed through the XML... but now turning that into JSON to resend back to the client is giving me some headaches.
NOTE: $resp is the response from eBay. It's their full length XML that is successfully parsed with the code below.
For example... $valueName could be Grade. And then I go into the next foreach loop and get the values for this. These values may be 10, 9.5, 9 etc.
Here is my PHP code.
$arrayName = array();
$arrayValue = array();
foreach($resp->aspectHistogramContainer->aspect as $name) {
$nameAspect = $name['name'];
//$arrayName["aspectName"] = $nameAspect;
foreach($name->valueHistogram as $value) {
$valueAspect = $value['valueName'];
//$arrayValue["aspectValue"] = $valueAspect;
}
//array_push($arrayName, $arrayValue);
}
echo json_encode($arrayName);
So, without me trying to create my own JSON, I am getting that I need. I echos results and it was similar to this...
NAME
----- Value
----- Value
----- Value
NAME
----- Value
NAME
etc etc
For a JSON response... Im looking for something like...
[
{
"name": "NAME",
"value": ["value", "value"]
}, {
"name": "name",
"value": ["value", "value"]
}
]
Any help and guidance would be greatly appreciated.
eBay's response is like this (there are A LOT more <aspect> and <valueHistogram>)
<getHistogramsResponse xmlns="http://www.ebay.com/marketplace/search/v1/services">
<ack>Success</ack>
<version>1.13.0</version>
<timestamp>2018-11-07T15:32:20.380Z</timestamp>
<aspectHistogramContainer>
<domainDisplayName>Baseball Cards</domainDisplayName>
<aspect name="Card Manufacturer">
<valueHistogram valueName="Ace Authentic">
<count>19</count>
</valueHistogram>
<valueHistogram valueName="American Caramel">
<count>2024</count>
</valueHistogram>
<valueHistogram valueName="APBA">
<count>10554</count>
</valueHistogram>
<valueHistogram valueName="Bazooka">
<count>8826</count>
</valueHistogram>
<valueHistogram valueName="Be A Player">
<count>17</count>
</valueHistogram>
<valueHistogram valueName="Bell Brand Dodgers">
<count>334</count>
To encode it (and assuming SimpleXML), then it's just a case of building each internal $aspect data array and then adding the values to it. I use (string) to ensure the data is not stored as a SimpleXMLElement, which can cause side effects...
$arrayName = array();
foreach($resp->aspectHistogramContainer->aspect as $name) {
$aspect = [ "name" => (string)$name['name']];
foreach($name->valueHistogram as $value) {
$aspect["value"][] = (string)$value['valueName'];
}
$arrayName[] = $aspect;
}
echo json_encode($arrayName);
with the sample XML, this gives...
[{"name":"Card Manufacturer","value":["Ace Authentic","American Caramel","APBA","Bazooka","Be A Player","Bell Brand Dodgers"]}]
Create one single array $resultArray and store values in it. By maintaining your current code structure with minimal changes, here is the updated code snippet,
$resultArray = array();
$i = 0; // Maintain Array Index value
foreach($resp->aspectHistogramContainer->aspect as $name) {
$resultArray[$i]["aspectName"] = (string)$name['name'];;
foreach($name->valueHistogram as $value) {
$resultArray[$i]["aspectValue"][] = (string)$value['valueName'];
}
$i++; // Increment array index to store next value
}
echo json_encode($resultArray);
$results = array();
// Parse the XML into a keyed array
foreach($resp->aspectHistogramContainer->aspect as $name) {
$nameAspect = (string) $name['name'];
$values = array();
foreach($name->valueHistogram as $value) {
$values[] = (string) $value['valueName'];
}
$results[$nameAspect] = $values;
}
// This keeps things simple - rewrite to the required JSON format
$outputForJSON = array();
foreach ($results as $name => $values) {
$outputForJSON[] = array(
"name" => $name,
"values" => $values
);
}
echo json_encode($outputForJSON);

update json replacing variable input from form in php

Greeting, I'm new to PHP, and currently looking for a way to edit json.
I have a form to input the key that wants to edit. I echo the input from form and successfully got the output showing but it didn't pass to json file to update. The code is as below.
function testfun()
{
// read file
$data = file_get_contents('Book2.json');
// decode json to array
$json_arr = json_decode($data, true);
foreach ($json_arr as $key => $value) {
if ($value['CELL_NAME'] == $_POST['in_cell']) {
$json_arr[$key]['#25'] = $_POST['in_remark'];
}
}
// encode array to json and save to file
file_put_contents('Book2.json', json_encode($json_arr));
}
//you this post contain test?
//test is the the button when i submit the form
if (array_key_exists('test',$_POST))
{
testfun();
}
Am I missing something?
Try my code.
function testfun()
{
// read file
$data = file_get_contents('Book2.json');
// decode json to array
$json_arr = array(json_decode($data, true));
foreach ($json_arr as $key => $value) {
if ($value['CELL_NAME'] == $_POST['in_cell']) {
$json_arr[$key]['#25'] = $_POST['in_remark'];
}
}
// encode array to json and save to file
file_put_contents('Book2.json', json_encode($json_arr));
}
if (array_key_exists('test',$_POST))
{
testfun();
}
As you mention in the comments, the content of the $json_arr is:
{"CELL_NAME":"1234A","#25":"remark value"}
So when you trying to access in:
foreach ($json_arr as $key => $value) {
if ($value['CELL_NAME'] == $_POST['in_cell']) {
$json_arr[$key]['#25'] = $_POST['in_remark'];
}
}
it has no key for $value at CELL_NAME key.
I guess your $data from the file should be like that (an array of JSONs):
$data = '[{"CELL_NAME":"1234A","#25":"remark value"}, {"CELL_NAME":"1234B","#25":"remark value"}]';
Now you can do this and it will work:
$arr = json_decode($data, true);
foreach ($arr as $key => $value) {
if ($value['CELL_NAME'] == "1234A") // you can change with $_POST['in_cell']
$arr[$key]['#25'] = "test"; // you can change with $_POST['in_remark']
}

PHP POST data assign to two dimensional array

I have a add-to-cart form to $_POST all data, and needed to store into a two dimensional array and assign to a session:
for example print_r($_POST) is:
Array("prod"=>"ZIU%3D","price"=>"68.00","alt-variation-1"=>"Red","alt-variation-2"=>"L","qty"=>"1")
to loop each $_POST:
foreach($_POST as $field => $value){
$f[] = $field;
$v[] = $value;
}
I looking for a way to assign above $f and $v into an array such as:
$new_product = array(array($f => $v));
and store in a session like:
$_SESSION['products'] = $new_product;
or any alternate way instead?
$_SESSION['products'][] = $_POST; would append the entire post array to the session products array, but you need to validate the data posted by the user.
A better way would be:
$data = $_POST;
// sanitise and validate $data here
$_SESSION['products'][] = $data;
An example for #HamzaZafeer:
foreach($_SESSION['products'] as $product){
echo $product['price'];
}
you can encode your array to JSON and store it in a session with:
$myJson = json_encode($_POST);
$_SESSION['myJson'] = serialize($myJson);

Database information into separate arrays

here is what I'm trying to do. I'm retrieving information from a database via array. What is happening is the information from the previous array is going into the next array.
Here is the code:
$i = 0;
foreach ($array_name as $key => test_name) {
$id = $test_name['id']
foreach ($test_name['id] as $key => $test_id {
$data = ModelClass::Information($test_id);
$array_name[$i]['new_infroamtion'] = $data'
}
}
So right now based on the code data from the table is correctly going into the first array, however, information based from the first array is going into the second array..
Let me know if you need anymore information.
Thank you
You are using $array_name while you are iterating through $array_name. This is valid code if you want to do this, but I don't think you do. You need to change the second $array_name to something else.
$i = 0;
foreach (**$array_name** as $key => test_name) {
$id = $test_name['id']
foreach ($test_name['id'] as $key => $test_id {
$data = ModelClass::Information($test_id);
**$array_name**[$i]['new_infroamtion'] = $data
}
}
I did find a solution. What I had to do was add the following
$s = array()
Then in the for loop, I added the following code:
foreach ($test_name['id] as $key => $test_id {
$data = ModelClass::Information($test_id);
$s[] = $data
$array_name[$i]['new_infroamtion'] = $s'
}

Categories