how to add Apostrophe in php native - php

I have a following string
$data = "20150825131738_262,20150825132227_241,20150825132254_898,20150825132320_209";
How to add ' in $data. So the resultant output is as follows
'20150825131738_262','20150825132227_241','20150825132254_898','20150825132320_209,20150825132346_124','20150825132406_744','20150825143522_447','20150828145011_928'
help me thank's

Following would give you the desired results
$data = "20150825131738_262,20150825132227_241,20150825132254_898,20150825132320_209";
$data_array = explode(',', $data);
$data = "'". implode("','", $data_array) . "'";
print_r($data);
See it running online here

Try This
$arr=explode(',', $data);
implode("','",$arr);

If you are getting this value from database or some other sources then you can simply use one of these ways using simple implode and explode function as
$data = "20150825131738_262,20150825132227_241,20150825132254_898,20150825132320_209";
echo "'".implode("','",explode(',',$data))."'";
or using preg_replace_callback as
$data = "20150825131738_262,20150825132227_241,20150825132254_898,20150825132320_209";
echo preg_replace_callback('/[\d_]+/',function($match){ return "'$match[0]'";},$data);

$data = "20150825131738_262,20150825132227_241,20150825132254_898,20150825132320_209";
$pad_data = "'" . $data . "'";
$data = str_replace (",", "', '", $pad_data);
echo $data;

A slightly different method from the other answers:
$data = '20150825131738_262,20150825132227_241,20150825132254_898,20150825132320_209';
# Split data into individual fields
$array = explode(',', $data);
# Surround each field with single quotes
$array = array_map(
function ($field) { return "'${field}'"; },
$array
);
# Join fields back into a single string again
$data = implode(',', $array);
echo $data;
The code can be seen running here.

Related

Send array value in a URL parameter

I'm having issues building a proper URL parameter sent to a service. I need to send dynamic query results in one parameter. Here's what I have reached so far:
<a href="https://serviceurl/?language=EN&variable1=<?php
$mobiles = array();
while($row_query = mysql_fetch_assoc($query))
{
$data = $row_query['rowwithvalues'];
$myArray = implode(',', $data);
foreach($myArray as $my_Array){
echo $my_Array;
}
}
?>&variable2=Hello">Test</a>
The above returns a blank value for variable1 in the url.
Thanks in advance!
When you calling $myArray = implode(',', $data); it makes $myArray string from implode doc:
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.
So you cannot loop on it - I guess you wanted to use explode. Try this:
<a href="https://serviceurl/?language=EN&variable1=
<?php
while($row_query = mysql_fetch_assoc($query)) {
$data = $row_query['rowwithvalues'];
$myArray = explode(',', $data);
foreach($myArray as $my_Array){
echo $my_Array;
}
}
?>&variable2=Hello">Test</a>

arraymap vs foreach loop when creating a comma delimited string

I'm creating a comma delimited string for an SQL query. I would like to know what is better arraymap or a foreach loop. Here are my two examples:
$group_ids = "";
foreach ($group_array as $group_id) {
$group_ids .= $group_id . ",";
}
$group_ids = rtrim($group_ids, ',');
vs
$group_ids = "";
array_map(function ($group_id) use ($group_ids) {
$group_ids .= $group_id . ",";
return;
}, $group_array);
$group_ids = rtrim($group_ids, ',');
Or is there a better way? Or is there literally not much difference?
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
from
http://php.net/manual/en/function.implode.php
would be more efficient
You can also use implode(',',$array_of_ids). Just make sure you trim your values before using the implode.
$ids = ['foo','bar','boo'];
$ids = array_map('trim',$ids);
$ids_list = implode(',',$ids);
echo $ids_list; # foo,bar,boo

Converting CSV file with column seperator to JSON

I have a CSV file (my_data.csv) that I want to convert to JSON object.
With column ";" it gives me wrong result, with comma "," it works fine.
But I don't want edit the csv file. And I don't want use str_replace because the csv file is huge and it will take longer.
How can I change my conversion function to generate the correct JSON format ?
Here is my CSV file:
"Timestamp";"Longitude";"Latitude";"Client";"Price"
"2015-08-01 05:10:13";10.714069;48.031952;"test1";17.2
"2015-08-01 05:10:13";10.714069;48.031952;"test2";17.2
"2015-08-01 05:10:13";10.714069;48.031952;"test3";17.2
"2015-08-01 05:10:13";10.714069;48.031952;"test4";17.2
This is my PHP code
$file="data/my_file.csv";
$csv= file_get_contents($file);
$rows = explode("\n", trim($csv));
$data = array_slice($rows, 1);
$keys = array_fill(0, count($data),$rows[0] );
$json = array_map(function ($row, $key) {
return array_combine(str_getcsv($key), str_getcsv($row));
}, $data, $keys);
$data=json_encode($json);
echo $data;
I get this :
[{"Timestamp;\"Longitude\";\"Latitude\";\"Client\";\"Price\"":"2015-08-01 05:10:13;10.714069;48.031952;\"test1\";17.2"},
{"Timestamp;\"Longitude\";\"Latitude\";\"Client\";\"Price\"":"2015-08-01 05:10:13;10.714069;48.031952;\"test2\";17.2"},
{"Timestamp;\"Longitude\";\"Latitude\";\"Client\";\"Price\"":"2015-08-01 05:10:13;10.714069;48.031952;\"test3\";17.2"},
{"Timestamp;\"Longitude\";\"Latitude\";\"Client\";\"Price\"":"2015-08-01 05:10:13;10.714069;48.031952;\"test4\";17.2"}]
It should be this :
[{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test1","Price":"17.2"},
{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test2","Price":"17.2"},
{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test3","Price":"17.2"},
{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test4","Price":"17.2"}]
You have to change
return array_combine(str_getcsv($key), str_getcsv($row));
to
return array_combine(str_getcsv($key, ';'), str_getcsv($row, ';'));
Because the default value of parameter $delimiter is ',':
array str_getcsv ( string $input [, string $delimiter = "," [, string
$enclosure = '"' [, string $escape = "\" ]]] )
Alternative solution:
<?php
$csvString = file_get_contents('/path/to/data.csv');
$csvRows = str_getcsv($csvString, "\n"); // split new lines, gives you rows
$rows = array();
foreach($csvRows as $row) {
$rows[] = str_getcsv($row, ";"); // parse the rows
}
// remove the first row. its the CSV column heading line. keep keys for reuse.
$itemKeys = array_shift($rows);
// run over all rows and combine keys with values, to get a named array
foreach($rows as $rowKeys => $rowValues) {
$array[] = array_combine($itemKeys, $rowValues);
}
echo json_encode($array);
Result:
[{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test1","Price":"17.2"},
{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test2","Price":"17.2"},
{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test3","Price":"17.2"},
{"Timestamp":"2015-08-01 05:10:13","Longitude":"10.714069","Latitude":"48.031952","Client":"test4","Price":"17.2"}]

Access JSON array in PHP and send to MySQL SELECT

I'm trying to receive the data from JSON with PHP and use it in my SELECT query. I have searched everywhere and every solution didn't worked for me.
My Returned JSON data:
"{processos:[{"processo":"203"},{"processo":"1430"}]}"
My PHP:
$ar2 = json_decode($processo2, true);
$where2 = array();
foreach($ar2['processo'] as $key=>$val){
$where2[] = $val;
}
$where2 = implode(',', $where2);
$pegaSonda = $pdo->prepare("SELECT * FROM sonda WHERE n_processo IN ($where2)");
$pegaSonda->execute();
What's wrong with my code?
EDIT
The code from #wadersgroup worked correctly, but when i change to my variable it stops. This is the way i'm encoding it:
$jsonData = array();
$jsonData[] = array("processo" => $automovel->n_processo);
$data['processo2'] .= '{"processos":'.json_encode($jsonData).'}';
$data['processo2'] is sending to my AJAX to populate the input and then it receive data back with:
$processo2 = strip_tags(stripslashes($_POST['n_processo2']));
There are many errors in this code. Try this
$ar2 = json_decode('{"processos":[{"processo":"203"},{"processo":"1430"}]}', true);
$where2 = array();
foreach($ar2['processos'] as $key=>$val){
$where2[] = $val['processo'];
}
$where = implode(',', $where2);
print_r($where);
Your JSON string looks invalid, try instead:
'{"processos":[{"processo":"203"},{"processo":"1430"}]}'
$processo2 = '{"processos": [{ "processo": "203"},{ "processo": "1430"}]}'
$ar2 = json_decode($processo2, true);
$arr = array_map(function($i) {return $i['processo']; }, $ar2["processos"]);
$where = implode(", ", $arr);

php implode (101) with quotes

Imploding a simple array
would look like this
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
and that would return this
lastname,email,phone
great, so i might do this instead
$array = array('lastname', 'email', 'phone');
$comma_separated = implode("','", $array);
$comma_separated = "'".$comma_separated."'";
and now i have what I want a nice pretty csv string
'lastname','email','phone'
is there a better way to do this, it feels to me like there should be an optional parameter for implode am I missing something ?
$array = array('lastname', 'email', 'phone');
echo "'" . implode("','", $array) . "'";
$ids = sprintf("'%s'", implode("','", $ids ) );
You could use array_map():
function add_quotes($str) {
return sprintf("'%s'", $str);
}
$csv = implode(',', array_map('add_quotes', $array));
DEMO
Also note that there is fputcsv if you want to write to a file.
No, the way that you're doing it is just fine. implode() only takes 1-2 parameters (if you just supply an array, it joins the pieces by an empty string).
Don't know if it's quicker, but, you could save a line of code with your method:
From
$array = array('lastname', 'email', 'phone');
$comma_separated = implode("','", $array);
$comma_separated = "'".$comma_separated."'";
To:
$array = array('lastname', 'email', 'phone');
$comma_separated = "'".implode("','", $array)."'";
If you want to use loops you can also do:
$array = array('lastname', 'email', 'phone');
foreach($array as &$value){
$value = "'$value'";
}
$comma_separated = implode(",", $array);
Demo: http://codepad.org/O2kB4fRo
$id = array(2222,3333,4444,5555,6666);
$ids = "'".implode("','",$id)."'";
Or
$ids = sprintf("'%s'", implode("','", $id ) );
Alternatively you can create such a function:
function implode_with_quotes(array $data)
{
return sprintf("'%s'", implode("', '", $data));
}
try this code :
$data = 'ABC,DEF,GHI';
$str = "'".str_replace(',',"','",$data)."'";
echo $str;
If you want to avoid the fopen/fputcsv sub-systems here's a snippet that builds an escaped CSV string from an associative array....
$output = '';
foreach ($list as $row) {
$output .= '"' . implode('", "', array_values($row)) . '"' . "\r\n";
}
Or from a list of objects...
foreach ($list as $obj) {
$output .= '"' . implode('", "', array_values((array) $obj)) . '"' . "\r\n";
}
Then you can output the string as desired.
Another possible option, depending on what you need the array for:
$array = array('lastname', 'email', 'phone');
echo json_encode($array);
This will put '[' and ']' around the string, which you may or may not want.
Don't forget to escape your data!
If you want to put data in a CSV file without fputcsv function or put it in a SQL query use this code:
$comma_separated = "'" . implode("','", array_map('addslashes', $array)) . "'";
This code avoids SQL injection or data fragmentation when input array contains single quotation or backslash characters.
Another solution is achieved using implode + preg_replace as follows:
$a = ['A', 'B', 'C'];
implode(',', preg_replace('/^(.*)$/', '"$1"', $a)); // "A","B","C"
$b = [];
implode(',', preg_replace('/^(.*)$/', '"$1"', $b)); // empty string
As you can see this also saves you from checking if the array is empty.
you can do it this way also
<?php
$csv= '\'' . join(array('lastname', 'email', 'phone'),'\',').'\'';
echo $csv;
?>
I think this is what you are trying to do
$array = array('lastname', 'email', 'phone');
echo "'" . implode("','", explode(',', $array)) . "'";

Categories