How to insert element before and after the data value? - php

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;
}

Related

CSV to Output an Array that contains a field with JSON data

Using Laravel 5.2 and I want to import a CSV and store the records in the database. Name, Surname and Contact Number will be core fields and anything else will just be additional data that I want to store as JSON in an additional info field
example
* | name | surname | contact_number | gender | race |"
* | piet | pokol | 0111111111 | male | race |"
will be stored like so:
* ['name'=>'piet','surname'=>'pokol', 'contact_number'=>'0111111111', 'additional_data'=>'{gender:"male", race:"green"}']
My question is,is it possible to combine an array with JSON array like this?
So far I have it working to make a traditional array with this code
foreach ($reader as $index => $row) {
if ($index === 0) {
$headers = $row;
} else {
$data = array_combine($headers, $row);
$array = array_merge($data, ['client_id' => $client_id, 'list_id' => $list_id]);
Customer::create($array);
}
}
But I need to JSON encode all the field that are not core fields and then add them to the array.
Any body have any advice on this?
Check the below code, it might help you. You can use result array to store in database.
<?php
$data = array(
'name'=> "My Name",
'surname'=> 'My Surname',
'contact_number'=> '0987456321',
'age'=> '38',
'gender'=> 'female',
'address'=> 'NewYork, USA',
);
$core = array('name','surname','contact_number');
$result = array();
$additional = array();
foreach($data as $key => $val) {
if(in_array($key, $core)) {
$result[$key] = $val;
} else {
$additional[$key]= $val;
}
}
if(count($additional)) {
$result['additional'] = json_encode($additional);
}
echo "<pre>";
print_r($result);
?>

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);

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

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)

php array replicate format in while loop

I want to output the result of a query so that the format is the same as:
$links = array(
'Link 1' => '/link1',
'Link 2' => '/link2'
);
So the query is
$query = "SELECT * FROM link";
$result = mysql_query($query, $connection) or die(mysql_error());
$row = mysql_fetch_assoc($result)
The field that need to be output are:
$row['link_title'] and $row['url']
This is probably a bit more complex then desired or necessary but would this work for you:
$a = 0;
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $k => $v) {
// Assumes table column name is 'link_title' for the link title
if ($k == 'link_title') {$title[$a] = $v;}
// Assumes table column name is 'url' for the URL
if ($k == 'url') {$url[$a] = $v;}
}
$a++;
}
$i = 0;
foreach ($title as $t) {
$links[$t] = $url[$i];
$i++;
}
print_r($links);
As #Class stated, if the link_title's never repeat than you could do something like this:
while ($row = mysql_fetch_assoc($result)) {
$array[$row['link_title']] = $row['url'];
}
Since the link_title's were unique both processes output:
Array (
[Moxiecode] => moxiecode.com
[Freshmeat] => freshmeat.com
)
Database table + contents:
id | link_title | url |
---+------------+---------------|
1 | Moxiecode | moxiecode.com |
---+------------+---------------|
2 | Freshmeat | freshmeat.com |
Are you looking for something like this:
$links = array();
while(foo){
$links[$row['link_title']] = $row['url'];
}
OR you can use which might cause overriding if the title is the same like in the example above
$link = array();
$title = array()
while($row = mysql_fetch_assoc($result)){
array_push($title, $row['link_title']);
array_push($link, $row['url']);
}
$links = array_combine($title, $link);
Also use PDO or mysqli functions mysql is deprecated. Here's a tutorial for PDO
EDIT: Example: http://codepad.viper-7.com/uKIMgp I don't know how to create a example with a db but its close enough.
You want to echo out the structure of the array?
foreach ($Array AS $Values => $Keys)
{
echo "Array Key: <b>". $Keys ."</b> Array Value:<b>". $Values ."</b>";
}
This will echo out the structure of your exampled array

PHP withdrawing attributes from database using explode

I'm searching the best way to withdraw some data from my MySQL field by I fail everytime. So here I come...
I got some data in my db which looks following: "attribute1=0::attribute2=1::attribute3=5 .. etc.".
Now I need to get that data so I can use it like this:
foreach($xxx as $attributeName => $attributeValue)
echo $attributeName . ' = ' . $attributeValue;
So the above will print smg like;
attribute1 = 0
attribute2 = 1
... etc.
Hope you understand and help me out with this.
Thank you in advance.
$final = array();
$str = "attribute1=0::attribute2=1::attribute3=5";
$pairs = explode('::', $str);
foreach ($pairs as $pair)
{
$keyValue = explode('=', $pair);
$final[$keyValue[0]] = $keyValue[1];
}
print_r($final);
So here is what you do:
$data = 'attribute1=0::attribute2=1::attribute3=5';
$data_tree = explode("::", $data);
foreach($data_tree as $node)
{
list($field,$value) = explode('=',$node);
echo $field.' : '.$value.'<br/>';
}
it will print:
attribute1 : 0
attribute2 : 1
attribute3 : 5
Good Luck!

Categories