I have a json.php file which delivers results like this:
{ "markers": [ {'a1_id':"4213CK58", etc.
The problem is that the Google Maps API doesn't like single quotes and so I need my results like this:
{ "markers": [ {"a1_id":"4213CK58", etc.
Replacing ' by " in the code doesn't deliver...
<?php
// Iterate over the rows
$nextRow= $result->nextRow();
$r = 1;
$info = array();
while ( $nextRow ) {
$nextColumn = $result->nextColumn();
// Has this column been printed already
if ( $unique )
{
$d = $result->getDataForField($unique);
if ( array_key_exists($d, $already) )
{
$nextRow= $result->nextRow();
continue;
}
$already[$d] = true;
}
echo '{';
// Iterate over the columns in each row
while ( $nextColumn )
{
// Get the variable
$variable = $result->getOutputVariable();
$name = $variable->getName(true);
$data = $result->getDataForField();
if ( !isset($info[$name]) ) {
$info[$name]['translate'] = $variable->shouldTranslate();
$info[$name]['type'] = $variable->getDataType();
$info[$name]['linkable'] = $variable->isLinkable();
}
// Translate the data if requested
if ( $info[$name]['translate'] ) {
$data = LQMTemplate::_($data);
}
$data = $variable->format($data, false);
$type = $info[$name]['type'];
if ( ($type == 'bool') or ($type == 'boolean') )
{
$data = $data ? '1' : '0';
echo "'$name':$data";
} elseif ( $encode ) {
// Can we use json_encode ?
// str_replace because some versions of PHP have a bug that will over escape forward slashes
echo "'$name':".str_replace('\\/', '/', json_encode($data));
} else {
$data = LQMUtility::jsonEscape($data, '"');
echo "'$name':\"$data\"";
}
// Conditionally print the next column
$nextColumn = $result->nextColumn();
if ( $nextColumn ) echo ",\n ";
}
// Conditionally print the next column
$nextRow = $result->nextRow();
echo $nextRow ? "},\n" : "}\n";
$r++;
}
unset($result);
echo ']}';
}
}
Create an array containing the data you want to encode and then use PHP's builtin json_encode() function.
Related
This is the data in the text file contain the data
I have already store the data in the array
enter image description here
<?php
if (!(isset($_GET['job_title']) && empty($_GET['job_title']))) {
$job_title = $_GET['job_title'];
echo $job_title;
$filename = __DIR__ . '/jobpost.txt';
if (file_exists($filename)) {
$data= null;
$allData = array();
$handle = fopen($filename, "r");
while (!feof($handle)) {
$onedata = fgets($handle);
if ($onedata != "") {
$data = explode("\t", $onedata);
$allData[] = $data;
}
}
echo "<pre>";
print_r($allData);
echo "</pre>";
} else {
echo "file does not exist";
}
} else {
echo "<p class=\"bg_danger\"> must enter the job title </p>";
}
?>
My question is when user enter an input "software engineering" and based on the input value, must retrieve the related the array.
First don't forget to filter/sanitize your user inputs.
Now Check while storing data into the array if you can create a array with keys as "software engineering"
if that's not possible you can loop through array once & create array you need
$arrNewDataArray = [];
foreach( $dataArray as $arr ){
$arrNewDataArray[$arr[1]] = $arr;
}
Then you will be able to check if user input value is present in the array & retrieve it like below.
$userinput = 'software engineering';
$arrayYouNeed = [];
if( isset( $arrNewDataArray[$userinput] ) ) {
$arrayYouNeed = $arrNewDataArray[$userinput];
}
Hello i want to unserialize an array in order to display the array values.
The way that the array is inserted to my db field is like this.
persons: "a:1:{i:0;s:55:"[{"value":"john: writer"},{"value":"john: producer"}]";}"
and the function i have done but i am not getting any results is this
$adDetails = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($adDetails as $feed) {
$feed->logo_pic = SITE_URL . $feed->logo_pic;
$feed->image_path = SITE_URL . $feed->image_path;
$feed->media_pic = SITE_URL . 'mediaPic/' . $feed->media_pic;
$personsArr = unserialize(array($feed->persons));
$personsText = " ";
if(!empty($personsArr)){
list($firstItem) = $personsArr;
foreach ($firstItem as $key => $value) {
foreach ($value as $valueInner) {
$personsText .= $valueInner.", ";
}
}
}
$feed->personsNew = $personsText;
}
$response['success'] = true;
$response['adDetails'] = $adDetails;
echo json_encode($response);
I am getting nothing on personsText although persons is persons: "a:1:{i:0;s:55:"[{"value":"john: writer"},{"value":"john: producer"}]";}"
Any help?
The value in the array is a JSON string, so you need to decode it.
The argument to unserialize() should just be $feed->persons, it shouldn't be in an array.
Instead of the loop, you can use array_column() to get all the value elements, and implode() to combine them with comma delimiters.
$adDetails = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($adDetails as $feed) {
$feed->logo_pic = SITE_URL . $feed->logo_pic;
$feed->image_path = SITE_URL . $feed->image_path;
$feed->media_pic = SITE_URL . 'mediaPic/' . $feed->media_pic;
$personsArr = unserialize($feed->persons);
$personsText = " ";
if(!empty($personsArr)){
$firstItem = json_decode($personsArr[0], true);
$personsText = implode(', ', array_column($firstItem, 'value'));
}
$feed->personsNew = $personsText;
}
$response['success'] = true;
$response['adDetails'] = $adDetails;
echo json_encode($response);
I want to decode array values for passing it into json. I want to pass the values in contentvalue baaed on content type into json. Now It shows null. I want to move array value as $zip_num=$content->zip; based on content type.
while ($ee = mysql_fetch_array($query)) {
$key_val = $ee['CONTENT_TYPE'];
$content = json_decode($ee['CONTENT_VALUE']);
if ($key_val == 'stat_sum') {
$stat = $content;
}
if ($key_val == 'zip_stats') {
$zip[] = $content;
$zip_num=$content->zip;
$zip_cou=$content->count;
}
if ($key_val == 'qual_stats') {
$qual[] = $content;
}
}
$new = array('ID'=>$id,'zip'=>$zip_num);
echo $json = json_encode($new);
}
Replace $key_val (that one which is in if statement) with $ee['CONTENT_TYPE']
I am getting the result from web service SOAP client. I have created an array to get the result and display it using json format. I am getting few of my results properly. I have SerialEquipment parameter which is array and i need to get the result using foreach loop. I am doing an mistake there. I dont know how can i assign my $vehiclResult array in this for each statement. So that all the results at last i will collect and display using json using vehicleResult array.My mistake is in the foreach loop.
structure for SerialEquipment parameters:
Code:
$vehicle = getVehicleValuation();
$Serial=$vehicle['SerialEquipment'];
$vehiclResult = array(
'WE_Number' => $vehicle['WE Number'] ."<br>",
'Vehicle Type'=> $vehicle['Vehicle Type'] . "<br>",
'HSN' => $vehicle['HSN'] . "<br>",
'TSN' => $vehicle['TSN'] . "<br>"
);
foreach($Serial as $key => $obj) {
if(!isset($vehiclResult[$key]))
$vehiclResult[$key] = array();
$vehiclResult[$key]['SerialEquipment'] = $key. "<br>";
$vehiclResult[$key]['Code'] = $obj->Code. "<br>";
$vehiclResult[$key]['Desc Short'] = $obj->Desc_Short. "<br>";
$vehiclResult[$key]['Desc Long'] = $obj->Desc_Long. "<br>";
foreach($obj->Esaco as $key2 => $obj2) {
if($obj2->EsacoMainGroupCode === null){
// doesn't contain Esaco
continue;
}
else{
if(!isset($vehiclResult[$key][$key2]))
$vehiclResult[$key][$key2] = array();
$vehiclResult[$key][$key2]['esaco'] = $key2. "<br>";
$vehiclResult[$key][$key2]['EsacoMainGroupCode'] = $obj2->EsacoMainGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoMainGroupDesc'] = $obj2->EsacoMainGroupDesc. "<br>";
$vehiclResult[$key][$key2]['EsacoSubGroupCode'] = $obj2->EsacoSubGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoSubGroupDesc'] = utf8_decode($obj2->EsacoSubGroupDesc). "<br>";
$vehiclResult[$key][$key2]['EsacoGroupCode'] = $obj2->EsacoGroupCode. "<br>";
$vehiclResult[$key][$key2]['EsacoGroupDesc'] = utf8_decode($obj2->EsacoGroupDesc). "<br>";
}
}
}
$result = array(
'vehicle' => $vehiclResult
);
echo json_encode($result);
die();
}
You need to check if your array have the key so:
if(!isset($vehiclResult[$key]))
if not, you need to create it:
$vehiclResult[$key] = array(); // as an array
Also, you don't really need to make a description of your "item". You can Parse your JSON on the result page to output some text.
You can do something like.
Do something like:
foreach($Serial as $key => $obj) {
if(!isset($vehiclResult[$key]))
$vehiclResult[$key] = array();
$vehiclResult[$key]['serial'] = $key;
$vehiclResult[$key]['code'] = $obj->Code;
$vehiclResult[$key]['short_desc'] = $obj->Desc_Short;
$vehiclResult[$key]['long_desc'] = $obj->Desc_Long;
foreach($obj->Esaco as $key2 => $obj2) {
if($obj2->EsacoMainGroupCode === null){
// doesn't contain Esaco
continue;
}
else{
if(!isset($vehiclResult[$key][$key2]))
$vehiclResult[$key][$key2] = array();
$vehiclResult[$key][$key2]['esaco'] = $key2;
$vehiclResult[$key][$key2]['EsacoMainGroupCode'] = $obj2->EsacoMainGroupCode;
$vehiclResult[$key][$key2]['EsacoMainGroupDesc'] = $obj2->EsacoMainGroupDesc;
$vehiclResult[$key][$key2]['EsacoSubGroupCode'] = $obj2->EsacoSubGroupCode;
$vehiclResult[$key][$key2]['EsacoSubGroupDesc'] = utf8_decode($obj2->EsacoSubGroupDesc);
$vehiclResult[$key][$key2]['EsacoGroupCode'] = $obj2->EsacoGroupCode;
$vehiclResult[$key][$key2]['EsacoGroupDesc'] = utf8_decode($obj2->EsacoGroupDesc);
}
}
}
$result = array(
'vehicle' => $vehiclResult
);
echo json_encode($result);
die();
If you would keep your "text" and your <br> code, do the samething but add what you want to output after the "="
EDIT
** A HAVE CHANGE THE CODE PREVIOUSLY..
if you want to test your $vehiclResult, try something like:
foreach($vehiclResult as $key=>$value){
if(!is_array($value))
var_dump($value);
else {
foreach($value as $key2=>$value2){
if(!is_array($value2))
var_dump($value2);
else {
foreach($value2 as $key3=>$value3){
var_dump($value3);
}
}
}
}
My code below show what I'm doing. Basically the aim is to retrieve data from a database and convert it to a JSON format for jQueryUI. With the method below and a method that didn't use the array_to_json function I was able to get JSON data returned. Eg.:
[ { "name": "Kurt Schneider" }, { "name": "Sam Tsui" }, { "name": "Christina Grimmie" } ]
But the issue is that it still doesn't function with the autocomplete. I replaced the below code with the search.php that was provided with the example, so it's obviously an issue with this code.
I began with only this code:
<?php
include 'connect.php';
mysql_select_db("database", $con);
$search = mysql_query("SELECT name FROM artist");
$rows = array();
while($row = mysql_fetch_assoc($search)) {
$result[] = $row;
}
print json_encode($result);
?>
Which achieved affectively the same results as the below code (besides some differences in spacing):
(The array_to_json function was copied direct from the example).
<?php
include 'connect.php';
mysql_select_db("database", $con);
$search = mysql_query("SELECT name FROM artist");
$rows = array();
while($row = mysql_fetch_assoc($search)) {
$result[] = $row;
}
function array_to_json( $array ){
if( !is_array( $array ) ){
return false;
}
$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
if( $associative ){
$construct = array();
foreach( $array as $key => $value ){
// We first copy each key/value pair into a staging array,
// formatting each key and value properly as we go.
// Format the key:
if( is_numeric($key) ){
$key = "key_$key";
}
$key = "\"".addslashes($key)."\"";
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "\"".addslashes($value)."\"";
}
// Add to staging array:
$construct[] = "$key: $value";
}
// Then we collapse the staging array into the JSON form:
$result = "{ " . implode( ", ", $construct ) . " }";
} else { // If the array is a vector (not associative):
$construct = array();
foreach( $array as $value ){
// Format the value:
if( is_array( $value )){
$value = array_to_json( $value );
} else if( !is_numeric( $value ) || is_string( $value ) ){
$value = "'".addslashes($value)."'";
}
// Add to staging array:
$construct[] = $value;
}
// Then we collapse the staging array into the JSON form:
$result = "[ " . implode( ", ", $construct ) . " ]";
}
return $result;
}
echo array_to_json($result);
?>
<?php
include 'connect.php';
mysql_select_db("database", $con);
$search = mysql_query("SELECT name FROM artist");
$rows = array();
while($row = mysql_fetch_assoc($search)) {
//don't add the array, just the name.
$result[] = $row["name"];
}
print json_encode($result);
?>
The code above should return the JSON
["Kurt Schneider", "Sam Tsui", "Christina Grimmie"]