PHP/JSON - Remove every occurence of certain character before another character - php

My JSON is encoding peculiarly, so I need to remove every quote before a right-opening bracket. (e.g. every " before a {) Is it possible to do this in PHP, and if so, how?
"{ I would want to remove every occurrence of the quote before the bracket.
JSON here: http://devticker.pw/json-data.php
Code here:
while($row = mysqli_fetch_array($result))
{
$data[] = '{"c": [{ "v": ' . $row['Timestamp'] . '"},{"v":' . $row['USD'] . '} ]}';
}
$str = json_encode(array("rows"=>$data));
$str = substr($str, 1);
$str = str_replace("\"{", "{", $str);
$str = '{"cols":[{"type":"string"},{"type":"number"}],' . $str;
$str = stripslashes($str);
echo $str;

Try
while($row = mysqli_fetch_array($result))
{
$data[] = array("c" => array(array( "v" => $row['Timestamp']), array("v" => $row['USD'] ))));
}
$rows = array("rows"=>$data));
$cols = array("cols" => array(array("type"=>"string"),array("type"=>"number")),$row);
$str = json_encode($cols);
echo $str;

The problem is you are generating part of the JSON manually and then encoding that string with json_encode, which is escaping the quotes that should not be escaped. This is wrong. Using str_replace to remove the escaping is a workarround, not the correct way to generate your JSON.
If you generate your JSON using only json_encode it works well. Something like this should work:
// your columns
$cols = array();
$cols[0] = array('type' => 'string');
$cols[1] = array('type' => 'number');
// your rows
$rows = array();
while ($row = mysqli_fetch_array($result)) {
$r = new stdClass();
$r->c = array();
$r->c[0] = array('v' => $row['Timestamp']);
$r->c[1] = array('v' => $row['USD']);
$rows[] = $r;
}
// the final result
$result = array(
'cols' => $cols,
'rows' => $rows
);
// don't forget this
header('Content-Type: application/json');
echo json_encode($result);

Really can't understand why you need to do this (and why you are manupulating raw JSON string), but you can simply use the string-replacement function of php, str_replace:
$your_json_string = str_replace("\"{", "{", $your_json_string);

What version of PHP are you using?
If 5.3 or greater than you can use this:
return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
Frameworks like drupal have handled this stuff - you could probably rip some code from here to roll your own json_encode function https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_json_encode/7

$json = str_replace('"{','{',$json)

Related

How to insert element before and after the data value?

code:
while($row = mysqli_fetch_assoc($result))
{
$data[] = array(
'city' => $row["city"],
'hotel' => $row["hotel_name"]
);
}
mysqli_close($con);
$results = json_encode($data);
$json = json_decode($results, true);
foreach($json as $fet)
{
$datas = $fet['city']." | ".$fet['hotel'].", ";
echo $datas;
}
In this code I have create an autocomplete text box and I want to add " before and after data my data look like:
delhi | Radisson, noida | Ramada Phuket Deevana Patong, noida | Eco Poplar
but I want like this:
"delhi | Radisson", "noida | Ramada Phuket Deevana Patong", "noida | Eco Poplar"
So, How can I do this ?
Thank You
Just put double quotes between single quotes: '"'
Improvements: You could save formatted strings while fetching the results. The JSON related functions are useless. Then output using implode()
$data = [];
while($row = mysqli_fetch_assoc($result))
{
// double quotes between single quotes
$data[] = '"' . $row["city"] . ' | ' . $row["hotel_name"] . '"';
}
mysqli_close($con);
// Here I removed useless json_encode/decode functions
// Then output strings separated by a coma
echo implode(', ', $data);
In your case, you'll have comma after last element, please try this code:
$data = [];
foreach($json as $fet) {
$data[] = "\"{$fet['city']} | {$fet['hotel']}\"";
}
echo implode(", ", $data);
implode(): http://php.net/manual/en/function.implode.php
$data[] = array(
'city' => $row["city"],
'hotel' => $row["hotel_name"]
);
$results = json_encode($data);
$json = json_decode($results, true);
foreach($json as $fet)
{
$datas = '"'.$fet['city']." | ".$fet['hotel'].'"';
echo $datas;
}

How to convert specific strings to int from dynamic json's url?

I would like to remove "" from a few strings from json which updates every few minutes (http://zergpool.com/api/status).
for example:
{"bitcore":{"name":"bitcore","port":3556,"coins":1,"fees":0,"hashrate":0,"workers":0,"estimate_current":"0.00001745","estimate_last24h":"0.00001756","actual_last24h":"0.00000","hashrate_last24h":105820474.1458},
Fields:
"estimate_current":"0.00001745" -> "estimate_current":0.00001745
"estimate_last24h":"0.00001756" -> "estimate_last24h":0.00001756
"actual_last24h":"0.00000" -> "actual_last24h":0.00000
Since the numbers change all the time, is it possible to write a PHP to convert them in real time? This is what I did.
<?php
$url = 'http://zergpool.com/api/status';
$data = file_get_contents($url);
$manage = json_decode($data,true);
//$aha = (int)preg_replace("/[^\d]+/","",$manage); // tried removing them like this... doesn't work.
echo json_encode($manage)
doesn't work :(
You can use this to remove quotes from numeric values in JSON.
$encoded = json_encode($data, JSON_NUMERIC_CHECK);
Supported in the versions >= PHP 5.3
echo str_replace( '"', '' ,$data);
will remove all the double quotes.
I don't understand why you are trying to remove the double quotes from the $manage line. You can just access the elements of the json that are returned in $manage and convert to float.
$firstString = $manage['bitcore']['estimate_current'];
$firstFloat = (float)$firstString;
var_dump($firstFloat);
or
echo 'floatval=' . floatval($firstString);
Try this:
$json = file_get_contents("https://www.ahashpool.com/api/status/");
$ar = json_decode($json, TRUE);
$filter = [];
foreach ($ar as $k => $sub_ar) {
foreach ($sub_ar as $sub_k => $sub_v) {
if(preg_match('/^[0-9]*\.[0-9]+$/', $sub_v)){
$filter[$k][$sub_k] = (float) $sub_v;
} else {
$filter[$k][$sub_k] = $sub_v;
}
}
}
echo "<pre>";
var_dump($filter);
die();

Need help php to json array

I am having a string below
$string = ot>4>om>6>we>34>ff>45
I would like the JSON output be like
[{"name":"website","data":["ot","om","we","ff"]}]
and
[{"name":"websitedata","data":["4","6","34","45"]}]
what I've tried
$query = mysql_query("SELECT month, wordpress, codeigniter, highcharts FROM project_requests");
$category = array();
$category['name'] = 'website';
$series1 = array();
$series1['name'] = 'websitedata';
while($r = mysql_fetch_array($query)) {
$category['data'][] = $r['month'];
}
$result = array();
array_push($result,$category);
array_push($result,$series1);
print json_encode($result, JSON_NUMERIC_CHECK);
but the above code is applicable only if the data are present in rows from a mysql table, what i want is achieve the same result with the data from the above string. that is
$string = ot>4>om>6>we>34>ff>45
NEW UPDATE:
I would like to modify the same string
$string = ot>4>om>6>we>34>ff>45
into
json output:
[
{
"type" : "pie",
"name" : "website",
"data" : [
[
"ot",
4
],
[
"om",
6
],
[
"we",
34
]
]
}
]
I have updated the answer please check the json part, I would like the php code.
regards
You can explode() on the >s, and then loop through the elements:
$string = "ot>4>om>6>we>34>ff>45";
$array1 = [
'name'=>'website',
'data'=>[]
]
$array2 = [
'name'=>'websitedata',
'data'=>[]
]
foreach(explode('>', $string) as $index => $value){
if($index & 1) //index is odd
$array2['data'][] = $value;
else //index is even
$array1['data'][] = $value;
}
echo json_encode($array1); //prints {"name":"website","data":["ot","om","we","ff"]}
echo json_encode($array2); //prints {"name":"websitedata","data":["4","6","34","45"]}
A solution using preg_match_all():
$string = "ot>4>om>6>we>34>ff>45";
preg_match_all('/(\w+)>(\d+)/', $string, $matches);
$array1 = [
'name'=>'website',
'data'=> $matches[1]
];
$array2 = [
'name'=>'websitedata',
'data'=> $matches[2]
];
echo json_encode($array1); //prints {"name":"website","data":["ot","om","we","ff"]}
echo json_encode($array2); //prints {"name":"websitedata","data":["4","6","34","45"]}
Update:
To get the second type of array you wanted, use this:
//since json_encode() wraps property names in double quotes (which prevents the chart script from working), you'll have to build the json object manually
$string = "ot>4>om>6>we>34>ff>45";
preg_match_all('/(\w+)>(\d+)/', $string, $matches);
$data = [];
foreach($matches[1] as $index => $value){
if(isset($matches[2][$index]))
$data[] = '["' . $value . '",' . $matches[2][$index] . ']';
}
$type = 'pie';
$name = 'website';
echo $jsonString = '[{type:"' . $type . '",name:"' . $name . '",data:[' . implode(',', $data) . ']}]'; // prints [{type:"pie",name:"website",data:[["ot",4],["om",6],["we",34],["ff",45]]}]
Update #2:
This code uses explode(), and although it's probably not the most efficient way of doing it, it works.
//since json_encode() wraps property names in double quotes (which prevents the chart script from working), you'll have to build the json object manually
$string = "ot>4>om>6>we>34>ff>45";
$keys = [];
$values = [];
foreach(explode('>', $string) as $key => $value){
if(!($key & 1)) //returns true if the key is even, false if odd
$keys[] = $value;
else
$values[] = $value;
}
$data = [];
foreach($keys as $index => $value){
if(isset($values[$index]))
$data[] = '["' . $value . '",' . $values[$index] . ']';
}
$type = 'pie';
$name = 'website';
echo $jsonString = '[{type:"' . $type . '",name:"' . $name . '",data:[' . implode(',', $data) . ']}]'; // prints [{type:"pie",name:"website",data:[["ot",4],["om",6],["we",34],["ff",45]]}]
This should work, though there are probably better ways to do it.
$string = "ot>4>om>6>we>34>ff>45";
$website = ["name" => "website", "data" => []];
$websiteData = ["name" => "websitedata", "data" => []];
foreach(explode(">", $string) as $i => $s) {
if($i % 2 === 0) {
$website["data"][] = $s;
} else {
$websiteData["data"][] = $s;
}
}
echo json_encode($website);
echo json_encode($websiteData);
A regex alternative:
preg_match_all("/([a-z]+)>(\d+)/", $string, $matches);
$website = ["name" => "website", "data" => $matches[1]];
$websiteData = ["name" => "websitedata", "data" => $matches[2]];
Try this code:
$string = 'ot>4>om>6>we>34>ff>45';
$string_split = explode('>', $string);
$data = array("name" => "website");
$data2 = $data;
foreach ($string_split as $key => $value)
{
if (((int)$key % 2) === 0)
{
$data["data"][] = $value;
}
else
{
$data2["data"][] = $value;
}
}
$json1 = json_encode($data, JSON_NUMERIC_CHECK);
$json2 = json_encode($data2, JSON_NUMERIC_CHECK);
echo $json1;
echo $json2;
Output:
{"name":"website","data":["ot","om","we","ff"]}
{"name":"website","data":[4,6,34,45]}
Regards.
Try this snippet:
$strings = explode('>', 'ot>4>om>6>we>34>ff>45');
// print_r($string);
$x = 0;
$string['name'] = 'website';
$numbers['name'] = 'websitedata';
foreach ($strings as $s)
{
if ($x == 0) {
$string['data'][] = $s;
$x = 1;
} else {
$numbers['data'][] = $s;
$x = 0;
}
}
print_r(json_encode($string));
echo "<br/>";
print_r(json_encode($numbers));
As usual - it is long winded but shows all the steps to get to the required output.
<?php //https://stackoverflow.com/questions/27822896/need-help-php-to-json-array
// only concerned about ease of understnding not code size or efficiency.
// will speed it up later...
$inString = "ot>4>om>6>we>34>ff>45";
$outLitRequired = '[{"name":"website","data":["ot","om","we","ff"]}]';
$outValueRequired = '[{"name":"websitedata","data":["4","6","34","45"]}]';
// first: get a key / value array...
$itemList = explode('>', $inString);
/* debug */ var_dump(__FILE__.__LINE__, $itemList);
// outputs ------------------------------------
$outLit = array();
$outValue = array();
// ok we need to process them in pairs - i like iterators...
reset($itemList); // redundant but is explicit
// build both output 'data' lists
while (current($itemList)) {
$outLit[] = current($itemList);
next($itemList); // advance the iterator.
$outValue[] = current($itemList);
next($itemList);
}
/* debug */ var_dump(__FILE__.__LINE__, $itemList, $outLit, $outValue);
// make the arrays look like the output we want...
// we need to enclose them as arrays to get the exact formatting required
// i do that in the 'json_encode' statements.
$outLit = array('name' => 'website', 'data' => $outLit);
$outValue = array('name' => 'websitedata', 'data' => $outValue);
// convert to JSON.
$outLitJson = json_encode(array($outLit));
$outValueJson = json_encode(array($outValue));
// show required and calculated values...
/* debug */ var_dump(__FILE__.__LINE__, 'OutLit', $outLitRequired, $outLitJson);
/* debug */ var_dump(__FILE__.__LINE__, 'OutValue', $outValueRequired, $outValueJson);

Json encode an entire mysql result set

I want to get json with php encode function like the following
<?php
require "../classes/database.php";
$database = new database();
header("content-type: application/json");
$result = $database->get_by_name($_POST['q']); //$_POST['searchValue']
echo '{"results":[';
if($result)
{
$i = 1;
while($row = mysql_fetch_array($result))
{
if(count($row) > 1)
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
echo ",";
}
else
{
echo json_encode(array('id'=>$i, 'name' => $row['name']));
}
$i++;
}
}
else
{
$value = "FALSE";
echo json_encode(array('id'=>1, 'name' => "")); // output the json code
}
echo "]}";
i want the output json to be something like that
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]}
but the output json is look like the following
{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]}
As you realize that there is comma at the end, i want to remove it so it can be right json syntax, if i removed the echo ","; when there's more than one result the json will generate like this {"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]} and that syntax is wrong too
Hope that everybody got what i mean here, any ideas would be appreciated
If I were you, I would not json_encode each individual array, but merge the arrays together and then json_encode the merged array at the end. Below is an example using 5.4's short array syntax:
$out = [];
while(...) {
$out[] = [ 'id' => $i, 'name' => $row['name'] ];
}
echo json_encode($out);
Do the json_encoding as the LAST step. Build your data structure purely in PHP, then encode that structure at the end. Doing intermediate encodings means you're basically building your own json string, which is always going to be tricky and most likely "broken".
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = array('id'=>$i, 'name' => $row['name']);
}
echo json_encode($data);
build it all into an array first, then encode the whole thing in one go:
$outputdata = array();
while($row = mysql_fetch_array($result)) {
$outputdata[] = $row;
}
echo json_encode($outputdata);

How can I easily remove the last comma from an array?

Let's say I have this:
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
foreach($array as $i=>$k)
{
echo $i.'-'.$k.',';
}
echoes "john-doe,foe-bar,oh-yeah,"
How do I get rid of the last comma?
Alternatively you can use the rtrim function as:
$result = '';
foreach($array as $i=>$k) {
$result .= $i.'-'.$k.',';
}
$result = rtrim($result,',');
echo $result;
I dislike all previous recipes.
Php is not C and has higher-level ways to deal with this particular problem.
I will begin from the point where you have an array like this:
$array = array('john-doe', 'foe-bar', 'oh-yeah');
You can build such an array from the initial one using a loop or array_map() function. Note that I'm using single-quoted strings. This is a micro-optimization if you don't have variable names that need to be substituted.
Now you need to generate a CSV string from this array, it can be done like this:
echo implode(',', $array);
One method is by using substr
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = "";
foreach($array as $i=>$k)
{
$output .= $i.'-'.$k.',';
}
$output = substr($output, 0, -1);
echo $output;
Another method would be using implode
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = array();
foreach($array as $i=>$k)
{
$output[] = $i.'-'.$k;
}
echo implode(',', $output);
I don't like this idea of using substr at all, since it's the style of bad programming. The idea is to concatenate all elements and to separate them by special "separating" phrases. The idea to call the substring for that is like to use a laser to shoot the birds.
In the project I am currently dealing with, we try to get rid of bad habits in coding. And this sample is considered one of them. We force programmers to write this code like this:
$first = true;
$result = "";
foreach ($array as $i => $k) {
if (!$first) $result .= ",";
$first = false;
$result .= $i.'-'.$k;
}
echo $result;
The purpose of this code is much clearer, than the one that uses substr. Or you can simply use implode function (our project is in Java, so we had to design our own function for concatenating strings that way). You should use substr function only when you have a real need for that. Here this should be avoided, since it's a sign of bad programming style.
I always use this method:
$result = '';
foreach($array as $i=>$k) {
if(strlen($result) > 0) {
$result .= ","
}
$result .= $i.'-'.$k;
}
echo $result;
try this code after foreach condition then echo $result1
$result1=substr($i, 0, -1);
Assuming the array is an index, this is working for me. I loop $i and test $i against the $key. When the key ends, the commas do not print. Notice the IF has two values to make sure the first value does not have a comma at the very beginning.
foreach($array as $key => $value)
{
$w = $key;
//echo "<br>w: ".$w."<br>";// test text
//echo "x: ".$x."<br>";// test text
if($w == $x && $w != 0 )
{
echo ", ";
}
echo $value;
$x++;
}
this would do:
rtrim ($string, ',')
see this example you can easily understand
$name = ["sumon","karim","akash"];
foreach($name as $key =>$value){
echo $value;
if($key<count($name){
echo ",";
}
}
I have removed comma from last value of aray by using last key of array. Hope this will give you idea.
$last_key = end(array_keys($myArray));
foreach ($myArray as $key => $value ) {
$product_cateogry_details="SELECT * FROM `product_cateogry` WHERE `admin_id`='$admin_id' AND `id` = '$value'";
$product_cateogry_details_query=mysqli_query($con,$product_cateogry_details);
$detail=mysqli_fetch_array($product_cateogry_details_query);
if ($last_key == $key) {
echo $detail['product_cateogry'];
}else{
echo $detail['product_cateogry']." , ";
}
}
$foods = [
'vegetables' => 'brinjal',
'fruits' => 'orange',
'drinks' => 'water'
];
$separateKeys = array_keys($foods);
$countedKeys = count($separateKeys);
for ($i = 0; $i < $countedKeys; $i++) {
if ($i == $countedKeys - 1) {
echo $foods[$separateKeys[$i]] . "";
} else {
echo $foods[$separateKeys[$i]] . ", \n";
}
}
Here $foods is my sample associative array.
I separated the keys of the array to count the keys.
Then by a for loop, I have printed the comma if it is not the last element and removed the comma if it is the last element by $countedKeys-1.

Categories