Quoting items when using implode function - php

I am trying to use the implode function on array; and its working fine and i am returning result fine as it should suppose to do. I would now like to add extra quotation marks at the start and end of each item.
EG: I am currently getting this result in implode:
jan,feb,march,april,etc,etc
Instead I would like each item to be quoted:
"jan","feb","march","april","etc","etc"
Here is little code how i am using to implode something from my array
$selectedMonths = implode(",",array_column($selectedMonths,'id'));
As it is already string, I tried this below code also, but it was of no use. as it is already a string, but when imploding the commas are not added.
foreach($selectedMonths as $value){
array_replace($selectedMonths,array_map('strval', array_slice($value, 0)));
}
Initially I am getting $selectedMonths as a json array, for which i have used json_decode() in php and in that foreach I have tried after converting the json array to associated array. But now how to add extra "" around every comma separated value?

This should work for you:
<?php
$array = array("jan", "feb", "march", "april", "etc", "etc");
echo '"' . implode('","', $array) . '"';
?>
Output:
"jan","feb","march","april","etc","etc"

It sounds like what you want to do, is get a JSON string from your array? For that you can use json_encode:
$json = json_encode($array);
But to append and prepend a quote mark to every string in an array, you can use array_map:
$array = ["jan","feb","march","april","etc","etc"];
$mapped = array_map($array, function($value) {
return '"' . $value . '"';
});

Related

Array Split In PHP

Now my array is Storing values like
Array([0] => "Aaa", "bbb", "ccc")
How can I make this Array as below using PHP
Array[0] = "Aaa", Array[1] = "bbb"
How to make like this. I tried with explode its not taking values correctly If anyone knows solution. Please help me to get out of this. Thanks in advance.
$oldarray[0]='"abc","def","hij"';
$oldarray[1]='"abc","def","hij"';
$newarray=array();
foreach ($oldarray as $value) {
$newarray[] = str_replace('"','',explode(',',$value));
//print_r($value);die();
}
print_r($newarray);
Use explode
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter comma.
$array1 = explode(',',$array[0]);
Use str_replace to remove double quotes
str_replace('"', '', $array[0]);
$array1 = explode(',',str_replace('"', '',$array[0]));
Check array1[0], array1[1] and array1[2] to find your values
Use explode to split the value in multiple values based on the coma, use str_replace to remove the quotes :
you do something like this
$newarray = explode(',',str_replace('"', "",$oldarray[]));
or:
$newarray = explode('","',trim($oldarray[],'"'));
docs

Extracting data from Json in Php

I have this Json Object Below, I want to extract this data and output it in PHP
{"seat_booked":"A5","0":"A5","1":"A3"}
then get them into this format
$seat_booked = "'A5', 'A5', 'A3'";
How can I do this?
I hope you are looking for this, its very simple example by using json_decode():
$string = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = json_decode($string,true);
$resuiredString = '"'."'".implode("','", $decoded)."'".'"';
echo $resuiredString;
Result:
"'A5','A5','A3'"
Side Note:
I suggest you to learn about variable concatenation.
PHP Concatenation
Another solution:
$json = '{"seat_booked":"A5","0":"A5","1":"A3"}';
$decoded = array_map(
function($val) {
return "'". $val."'";
},
array_values(json_decode($json, true))
);
To get an object from a json in php you can use json_decode has explained here.
But you have another problem, your json is wrong!
If you want to represent a single dimensional array you should at least do this
["A5","A5","A3"]
Finally, using json_decode:
$obj = json_decode('["A5","A5","A3"]');
var_dump($obj);
Also, you could do something like:
{"0":"A5","1":"A5","2":"A3"}
$obj = json_decode('{"0":"A5","1":"A3", "2": "A5"}', true);
var_dump($obj);
Edit:
It's not very clear from your question if you are trying to get back an object from a json or if you just want to get a string from it.
If what you need is an string then you don't even need json, you could do this by string manipulation and/or using regex.
But just for completeness, if a quoted comma separated string is what you need you can do this:
$array = json_decode('["A5","A5","A3"]');
$str = implode("','",$array);
$str = "'" . $str . "'";
var_dump($str);

Prepared String Before Comma

I've got an array;
Array
(
[0] => Test1
[1] => Test2
[2] => Test3
)
Now I've used the Implode Function from which i got the comma separated String:
Test1, Test2, Test3
now I'd like to put a quotes ("") before and after every word e.g.
"Test1", "Test2", "Test3"
How could I change it to work how I want.
Try this simple one-liner:
$quotedStrings = '"' . implode('","', $myArray) . '"';
The "glue" parameter may be a complex string, though you only have to put the " at the beginning and end.
While the answer from Axel is totally fine for the given szenario,
using array_map along with implode will also work.
And this has the advantage, that modifications to each element are not limited to the start/end of the element. For instance, you can turn each entry to lower-case as well, or perform other, more complex operations, before applying implode.
$quotedString = implode(",", array_map("myCallback", $myArray));
function myCallback($entry){
//here you can to whatever you like to EACH element.
return '"'.$entry.'"';
}
Consider this an option
You can use make a new array by using foreach loop and then use implode. Use the code below
<?php
$array = array("Test1","Test2","Test3");
$quotes = array();
foreach($array as $p){
$quotes[] = '"'.$p.'"';
}
echo implode(",",$quotes); // Outputs "Test1","Test2","Test3"
?>
Another way you can do it by enclosing the implode in "" quotes and then implode comma , in quotes.
<?php
$array = array("Test1","Test2","Test3");
echo '"'.implode('","',$array).'"'; // Outputs "Test1","Test2","Test3"
?>
Hope this helps you

Add double quote between text seperated by comma [duplicate]

This question already has answers here:
PHP: How can I explode a string by commas, but not wheres the commas are within quotes?
(2 answers)
Closed 8 years ago.
I'm trying to figure out how to add double quote between text which separates by a comma.
e.g. I have a string
$string = "starbucks, KFC, McDonalds";
I would like to convert it to
$string = '"starbucks", "KFC", "McDonalds"';
by passing $string to a function. Thanks!
EDIT: For some people who don't get it...
I ran this code
$result = mysql_query('SELECT * FROM test WHERE id= 1');
$result = mysql_fetch_array($result);
echo ' $result['testing']';
This returns the strings I mentioned above...
Firstly, make your string a proper string as what you've supplied isn't. (pointed out by that cutey Fred -ii-).
$string = 'starbucks, KFC, McDonalds';
$parts = explode(', ', $string);
As you can see the explode sets an array $parts with each name option. And the below foreach loops and adds your " around the names.
$d = array();
foreach ($parts as $name) {
$d[] = '"' . $name . '"';
}
$d Returns:
"starbucks", "KFC", "McDonalds"
probably not the quickest way of doing it, but does do as you requested.
As this.lau_ pointed out, its most definitely a duplicate.
And if you want a simple option, go with felipsmartins answer :-)
It should work like a charm:
$parts = split(', ', 'starbucks, KFC, McDonalds');
echo('"' . join('", "', $parts) . '"');
Note: As it has noticed in the comments (thanks, nodeffect), "split" function has been DEPRECATED as of PHP 5.3.0. Use "explode", instead.
Here is the basic function, without any checks (i.e. $arr should be an array in array_map and implode functions, $str should be a string, not an array in explode function):
function get_quoted_string($str) {
// Here you will get an array of words delimited by comma with space
$arr = explode (', ', $str);
// Wrapping each array element with quotes
$arr = array_map(function($x){ return '"'.$x.'"'; }, $arr);
// Returning string delimited by comma with space
return implode(', ', $arr);
}
Came in my mind a really nasty way to do it. explode() on comma, foreach value, value = '"' . $value . '"';, then run implode(), if you need it as a single value.
And you're sure that's not an array? Because that's weird.
But here's a way to do it, I suppose...
$string = "starbucks, KFC, McDonalds";
// Use str_replace to replace each comma with a comma surrounded by double-quotes.
// And then shove a double-quote on the beginning and end
// Remember to escape your double quotes...
$newstring = "\"".str_replace(", ", "\",\"", $string)."\"";

Remove last character from a string [duplicate]

This question already has answers here:
How do I remove all specific characters at the end of a string in PHP?
(10 answers)
Closed 12 months ago.
I have a list of country as an array .. i want this array in following format to later return it via ajax :-
"india","usa","uk" ..
Used following code to get somewhat i was looking for ..
foreach($country_list as $country) {
$countries .= '"'.$country['label'].'",';
}
problem is it is giving output like "india","usa","uk", ... i.e with trailing comma .
Tried to remove it with
substr_replace($countries, "0", -1);
and
rtrim($countries, ",");
But didnt work ! .. Please help !
I think that you're missing to assign the variable back after the trim:
$s = '"india","usa","uk",';
$s = rtrim($s, ',');
// prints "india","usa","uk"
print $s;
Demo
Try before buy
try this substr() or mb_substr()
substr($string, 0, -1);
mb_substr($string, 0, -1);
or check this link
Have you tried using: str_replace(",", " ", $countries);
This function should replace each occurence of a comma with a space.
if (strlen($b) > 1){
$b = substr($b,0, -1);
}
Try this
$countries = [];
foreach($country_list as $country) {
$countries[] = $country['label'];
}
$new_array = implode(",", $countries);
Use implode instead:
$arr = array();
foreach($country_list as $country)
array_push($arr, $country['label']);
$comma_separated = implode(",", $arr);
Try this
create a variable ($comsep) and initialise it to an empty string.
in the foreach loop concatenate the variable ($comsep) at the start of the string.
add an extra statement in the foreach loop to set the variable ($comsep) to the value "," - after the concatenation statement.
This will put a comma at the start of each appended string except for the first one. The is no longer a trailing comma to deal with so no need to try trimming it off.
// Try to use chop() function in php. It helps in removing last character from a string
<?php
echo '<br>' .$country_name = "'USA','UK','India',";
echo '<br>' .chop($country_name,",");
exit;
?>
Output : 'USA','UK','India'
foreach($country_list as $country) {
$countries[] = $country['label'];
}
json_encode($countries);

Categories