how can split the result set array to string in php - php

i need help. i was developed a page in smarty , i got a result set from a query and i need to change the result set to string and stored in text area
my query is given below
select val from test
my result set is print in var_dump in controller
{ [0]=> array(1) { ["val"]=> string(1) "c" } [1]=> array(1) { ["val"]=> string(3) "c++" } [2]=> array(1) { ["val"]=> string(4) "java" } [3]=> array(1) { ["val"]=> string(3) "PHP" } }
i need to change in to sting like c,c++,java,PHP
the changing function is preformed only controller
ple help me.. and thk adv

Use foreach for that. See more information here - http://php.net/manual/en/control-structures.foreach.php .
Example -
$array = Array("333", "222", "111");
foreach($array as $string) {
echo $string.'<br />';
}
Another solution would be to use implode.
See more information here - http://php.net/manual/en/function.implode.php and again a small example -
$array = Array("333", "222", "111");
$strings = implode(",", $array); // comma in first quotes are seperator, you can set it also to " " for a single space.
echo $strings; // In this case it will output 333,222,111 if you would set it to empty space then it would output 333 222 11
EDIT:
For writing in file you must use file functions.
Check this link - http://php.net/manual/en/function.file-put-contents.php
example -
// your file
$file = 'sample.txt';
$array = Array("333", "222", "111");
// Add all strings to $content.
foreach($array as $string) {
$content .= $string.'<br />';
}
// write everything in file
file_put_contents($file, $content);
Suggestion:
When you are writing SQL queries, I would suggest that you already now start learning to write them correctly, so they are easier to read.
For example, your query -
select val from test
Could be changed to -
SELECT `val` FROM `test`
which is alot easier to read and understand.

If You need to join all array with some delimeters, then use implode.
Example:
$arr = array("hi", "peter!", "how", "are", "you");
echo implode(" ", $arr) . "?";
//output
// hi peter! how are you?

If you want a string separated by commas, you must use the implode function
string implode ( string $glue , array $pieces )
glue: Defaults to an empty string. This is not the preferred usage of implode() as glue would be the second parameter and thus, the bad prototype would be used.
pieces:The array of strings to implode.
Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element.
http://www.php.net/manual/en/function.implode.php
Example
$array = Array("333", "222", "111");
$string = explode(',', $array);
returns
"333,222,111"
if you want spaces:
$string = explode(' ', $array);
returns
"333 222 111"

Related

Separating Values from a String in PHP

I have a string comma separated where I want to get 2 values in variables. How can I accomplish it.
$responseData = "Data: invoice=1216,card=AMEX";
I am looking for value of Invoice and Card.
I tried using instring but not getting value I want.
sscanf()
You can use sscanf() to achieve this result.
sscanf() takes the same format as printf(), allowing you to provide a variable and expected format string, and will return the matching results.
For example:
list($invoice, $card) = sscanf($responseData, "Data: invoice=%d,card=%s");
var_dump($invoice); // int(1216)
var_dump($card); // string(4) "AMEX"
Community wiki of Mark Baker's answer in the comments above.
explode()
You can also do this manually by breaking up the string by delimiters with explode(). The Data: component is irrelevant, so trim it off, then split by commas, then split by = to get a key => value pair.
For example:
// Remove the Data: component
$responseData = ltrim($responseData, 'Data: ');
$example = array();
// Split by commas
foreach (explode(',', $responseData) as $value) {
// Split by equals
list ($k, $v) = explode('=', $value);
$example[$k] = $v;
}
var_dump($example);
// array(2) {
// ["invoice"]=>
// string(4) "1216"
// ["card"]=>
// string(4) "AMEX"
// }
preg_match()
Here is the preg_match version using named subpatterns:
$subject = 'Data: invoice=1216,card=AMEX';
$matches = [];
preg_match('/Data: invoice=(?<invoice>\d+),card=(?<card>\w+)/', $subject, $matches);
var_dump($matches['invoice']); // string(4) "1216"
var_dump($matches['card']); // string(4) "AMEX"

Remove phrases from string

I have a string like this:
..., "test1#test1.com" <test1#test1.com>, "test2#test2.com" <test2#test2.com>, "test3#test3.com", "test4#test4.com" <test4#test4.com>, ....
I am exploding everything by , , but problem is that i dont want to have value laike this
[0] => "test1#test1.com" <test1#test1.com> i need to remove the emails which are in those <..> brackets.
So the result should be like this [0] => test1#test1.com.
Any offers how to drop the second phrase?
You can make use of a function that has been especially tailored for such email address lists, for example imap_rfc822_parse_adrlist. Mapping it and extracting the information you need might do it already:
$list = ""test1#test1.com" <test1#test1.com>, "test2#test2.com" <test2#test2.com>, "test3#test3.com", "test4#test4.com" <test4#test4.com>";
$adresses = array_map(function($entry) {
return sprintf('%s#%s', $val->mailbox, $val->host);
}, imap_rfc822_parse_adrlist($list, ""));
This has the benefit that it properly deals with the quoted printable text in front that you have - which done properly is non-trivial (really).
The simplest way here - use strip_tags function (see strip_tags description)
<?php
$str = '"test1#test1.com" <test1#test1.com>';
$str= preg_replace("(<.*>+)", "", $str);
print $str;
?>
Use Regular Expressions to replace anything between <...> for empty strings, then explode your modified string into an array.
You can explode your text into an array and the run a array_map with a function that cleans your text. Something like this:
function clean($t){
//Use regexp to replace desired text
return preg_replace('/<[^>]*>/', '', $t);
}
$text = '"test1#test1.com" <test1#test1.com>, "test2#test2.com" <test2#test2.com>, "test3#test3.com", "test4#test4.com" <test4#test4.com>';
$a = explode(',', $text);
var_dump($a);
$b = array_map("clean", $a);
var_dump($b);
The easiest way is to use preg_match:
preg_match('(<.*>+)', $your_emails, $matches);
print_r($matches); // array of zero or more matches depending on input
if
$yourString='"test1#test1.com" <test1#test1.com>';
you can use:
$yourString=substr($yourString,1,strpos($yourString,'<')-3);
(edited)
It's a line of code:
array_map(function($a){ return trim($a, ' "'); }, explode(',', strip_tags($string)));
And the whole:
<?php
$string = <<<TK
"test1#test1.com" <test1#test1.com>, "test2#test2.com" <test2#test2.com>, "test3#test3.com", "test4#test4.com" <test4#test4.com>
TK;
$result = array_map(
function($a){
return trim($a, ' "');
},
explode(',', strip_tags($string))
);
var_dump($result);
Output:
array(4) {
[0]=>
string(15) "test1#test1.com"
[1]=>
string(15) "test2#test2.com"
[2]=>
string(15) "test3#test3.com"
[3]=>
string(15) "test4#test4.com"
}

Explode String in PHP

If I have a string "123x456x78", how could I explode it to return an array containing "123" as the first element and "456" as the second element? Basically, I want to take strings that are followed by "x" (which is why "78" should be thrown out). I've been messing around with regular expressions, but am having trouble.
Thanks!
EDIT: if the string were "123x456x78x" I would need three elements: "123", "456", "78". Basically, for each region following an "x", I need to record the string up until the next "x".
Loads of different ways, but here's a RegEx as you were trying that:
$str = "123x456x78";
preg_match_all("/(\d+)x/", $str, $matches);
var_dump($matches[1]);
Output:
array(2) { [0]=> string(3) "123" [1]=> string(3) "456" }
$arr = explode("x", "123x456x78");
and then
unset($arr[2]);
if you really can't stand that poor 78.
use explode
$string='123x456x78';
$res = explode('x', $string);
if(count($res) > 0) {
echo $res[0];
if(count($res) > 1) {
echo $res[1];
}
}
$var = "123x456x78";
$array = explode("x", $var);
array_pop($array);
To explode AND remove the last result:
$string='123x456x78'; // original string
$res = explode('x', $string); // resulting array, exploded by 'x'
$c = count($res) - 1; // last key #, since array starts at 0 subtract 1
unset($res[$c]); // unset that last value, leaving you with everything else but that.
While I'm all for regular expressions, in this case it might be easier to just use PHP's array functions...
$result=array_slice(explode('x',$yourstring),0,-1);
This should work because only the last element returned by explode won't be followed by an 'x'. Not sure if explode will add an empty string as the last element if it ends on 'x' though, you might have to test that...
Use this below code to explode. It works well!
<?php
$str='123x456x78';
$res=explode('x',$str);
unset($res[count($res)-1]); // remove last array element
print_r($res);
?>

PHP json-like-string split

I have this $str value :
[{\"firstname\":\"guest1\",\"lastname\":\"one\",\"age\":\"22\",\"gender\":\"Male\"},{\"firstname\":\"guest2\",\"lastname\":\"two\",\"age\":\"22\",\"gender\":\"Female\"}]
I want to split it into the following:
firstname:guest1,lastname:one,age:22
firstname:guest2,lastname:two,age:22
I tried explode (",",$str) , but it explode all using , as delimiter and I don't get what I want
anyone can help me ?
As Josh K points out, that looks suspiciously like a JSON string. Maybe you should do a json_decode() on it to get the actual data you're looking for, all organized nicely into an array of objects.
EDIT: it seems your string is itself wrapped in double quotes ", so you'll have to trim those away before you'll be able to decode it as valid JSON:
$str_json = trim($str, '"');
$guests = json_decode($str_json);
var_dump($guests);
I get this output with the var_dump(), so it's definitely valid JSON here:
array(2) {
[0]=>
object(stdClass)#1 (4) {
["firstname"]=>
string(6) "guest1"
["lastname"]=>
string(3) "one"
["age"]=>
string(2) "22"
["gender"]=>
string(4) "Male"
}
[1]=>
object(stdClass)#2 (4) {
["firstname"]=>
string(6) "guest2"
["lastname"]=>
string(3) "two"
["age"]=>
string(2) "22"
["gender"]=>
string(6) "Female"
}
}
JSON (JavaScript Object Notation) is not CSV (comma-separated values). They're two vastly different data formats, so you can't parse one like the other.
To get your two strings, use a loop to get the keys and values of each object, and then build the strings with those values:
foreach ($guests as $guest) {
$s = array();
foreach ($guest as $k => $v) {
if ($k == 'gender') break;
$s[] = "$k:$v";
}
echo implode(',', $s) . "\n";
}
Output:
firstname:guest1,lastname:one,age:22
firstname:guest2,lastname:two,age:22
(Assuming you do want to exclude the genders for whatever reason; if not, delete the if ($k == 'gender') break; line.)
If you split on ,'s then you will get all the other crap that surrounds it. You would then have to strip that off.
Looks a lot like JSON data to me, where is this string coming from?
If that is valid json, just run it through json_decode() to get a native php array...
Note that you may need to run it through stripslashes() first, as it appears you may have magic_quotes_gpc set... You can conditionally call it by checking with the function get_magic_quotes_gpc:
if (get_magic_quotes_gpc()) {
$_POST['foo'] = stripslashes($_POST['foo']);
}
$array = json_decode($_POST['foo']);
You need to use preg_replace function.
$ptn = "/,\\"gender\\":\\"\w+\\"\}\]?|\\"|\[?\{/";
$str = "[{\"firstname\":\"guest1\",\"lastname\":\"one\",\"age\":\"22\",\"gender\":\"Male\"},{\"firstname\":\"guest2\",\"lastname\":\"two\",\"age\":\"22\",\"gender\":\"Female\"}]";
$rpltxt = "";
echo preg_replace($ptn, $rpltxt, $str);
You can the php regular expression tester to test the result.
or use preg_match_all
$ptn = "/(firstname)\\":\\"(\w+)\\",\\"(lastname)\\":\\"(\w+)\\",\\"(age)\\":\\"(\d+)/";
$str = "[{\"firstname\":\"guest1\",\"lastname\":\"one\",\"age\":\"22\",\"gender\":\"Male\"},{\"firstname\":\"guest2\",\"lastname\":\"two\",\"age\":\"22\",\"gender\":\"Female\"}]";
preg_match_all($ptn, $str, $matches);
print_r($matches);
i still haven't get a chance to retrieve the JSON :
I var_dump the trimmed value as :
$str_json = trim($userdetails->other_guests, '"');
$guests = json_decode($str_json);
var_dump($str_json,$guests);
WHERE $userdetails->other_guests is the $str value I had before...
I get the following output :
string(169) "[{\"firstname\":\"guest1\",\"lastname\":\"one\",\"age\":\"22\",\"gender\":\"Male\"},{\"firstname\":\"guest2\",\"lastname\":\"two\",\"age\":\"23\",\"gender\":\"Female\"}]"
NULL
This mean the decoded json are NULL... strange

comma-separated string to array

I'm looking for the simplest way to take a single variable such as:
$variable = 'left,middle,right';
and write it to an array(); split at the commas.
$array = explode(',', $variable);
In case you string gets a little bit more complex (i.e. elements can be in quotes and both the delimiter and the quoting character can appear within an element) you might also be interested in fgetcsv() and str_getcsv()
$variable = '"left,right","middle", "up,down"';
$row = str_getcsv($variable);
var_dump($row);
prints
array(3) {
[0]=>
string(10) "left,right"
[1]=>
string(6) "middle"
[2]=>
string(7) "up,down"
}
you can also use preg_split()
$variable = 'left , middle, right';
print_r ( preg_split("/\s*,\s*/",$variable));

Categories