PHP grouping by data value - php

My data variable:
1=icon_arrow.gif,2=icon_arrow.gif,3=icon_arrow.gif
I need it to be grouped by the value after =, so in this case it should look like this:
$out = array('icon_arrow.gif' => '1, 2, 3');
The 'icon_arrow.gif' field need to be unique, and can't repeat.
How it can be done?

Initialize an array:
$array = array();
Explode the input by ,, store results as an array based on a sub-explode of it by =:
foreach(explode(',', $string) as $p)
{
list($i, $n) = explode('=',$p);
$array[$n][] = $i;
}
Implode then the result with ,:
foreach($array as &$v)
$v = implode(', ', $v);
unset($v);
Done.

Just for fun. With no special chars this should also work.
$str="1=icon_arrow.gif,2=icon_arrow.gif,3=icon_arrow.gif,4=x.gif";
$str = str_replace(',', '&', $str);
parse_str($str, $array);
$result = array();
foreach($array as $k=>$v)
$result[$v] = (isset($result[$v]) ? $result[$v] . ", " : "") . $k;

Related

How to explode in foreach loop and implode to one string

i need to explode a string in peaces and delete some caracters. Finally i would like to put this string horizontally together.
This is what i try:
$string = "34 asdfadfadf.*****23 vgadfsdfasdf.*****46 asdfasdfadf.";
$arr = explode("*****", $string);
foreach ($arr as $val) {
$val = trim(substr($val, 0, 2));
$arr_neu[] = $val;
}
$array_neu = implode(" ", $arr);
fwrite($flog, "\nstring neu:" . $array_neu);
and this is what i get:
34 asdfadfadf.*****23 vgadfsdfasdf.*****46 asdfasdfadf. 34 23 46
I only need the numbers 34 23 46!
thanks!
Simply with preg_replace function:
$s = '34 asdfadfadf.*****23 vgadfsdfasdf.*****46 asdfasdfadf.';
$result = trim(preg_replace('/[^0-9 ]+/', '', $s));
print_r($result);
The output:
34 23 46
----------
If the string could contain multiple consecutive spaces - change the above approach to the following:
$result = trim(preg_replace('/[^0-9]+/', ' ', $s));
At the end of code you are using wrong variable to implode data
change your code to
$string = "34 asdfadfadf.*****23 vgadfsdfasdf.*****46 asdfasdfadf.";
$arr = explode("*****", $string);
foreach ($arr as $val) {
$val = trim(substr($val, 0, 2));
$arr_neu[] = $val;
}
$array_neu = implode(" ", $arr_neu); // <--------change here. Use $arr_neu
fwrite($flog, "\nstring neu:" . $array_neu);
you just change implode value to $arr_neu instead of $arr
<?php
$string = "34 asdfadfadf.*****23 vgadfsdfasdf.*****46 asdfasdfadf.";
$arr = explode("*****", $string);
foreach ($arr as $val) {
$val = trim(substr($val, 0, 2));
$arr_neu[] = $val;
}
$array_neu = implode(" ", $arr_neu);
fwrite($flog, "\nstring neu:" . $array_neu);

php multiple array multiple explode

Php code
<?php
$d1 = "a:1,b:2,c:3,d:4"; //field number variable.. sometimes 4 or 10
$d2 = explode(',', $d1);
foreach ($d2 as $key => $value) {
$arr1 = explode(':',$d2[$key]);
foreach ($arr1 as $key1 => $value1) {
$arr1[] = $key1;
}
echo $arr1[0] . "," . $arr1[1] . ",";
}
?>
Result
a,1,b,2,c,3,d,4,
Fields (a,b,c,d) (field number variable.. sometimes 4 or 10..)
Values (1,2,3,4)
Expected result
Insert into Table1 (a,b,c,d) values (1,2,3,4)
How can i do to make this result ? (it would be good if it is a complete example)
Thanks for all answers
I know preg_split() will do the task fine. But last day when I got the similar problem I did this solution with the help of http://php.net/manual/en/function.explode.php#111307
function multiexplode ($delimiters,$string) {
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch;
}
$d1 = "a:1,b:2,c:3,d:4";
$result = implode(',',multiexplode(array(",",".","|",":"),$d1));
echo $result;
See demo : https://eval.in/871705
Edit: As per comment by SO
$d1 = "a:1,b:2,c:3,d:4"; //field number variable.. sometimes 4 or 10
$d2 = explode(',', $d1);
$result = [];
foreach ($d2 as $key => $value) {
list($k,$v) = explode(':',$value);
$result[$k] = $v;
}
print '<pre>';
print_r($result);
print '</pre>';
echo "INSERT INTO table1 (".implode(', ',array_keys($result)). ") VALUES (".implode(', ',array_values($result)). ")";
In recent PHP versions you can destructure the result of explode() on $d2[$key] (you should improve your naming, it helps!) into two separate arrays like so:
$keys = $values = [];
foreach (explode(',', $d1) as $parameter)
[$keys[], $values[]] = explode(':', $parameter);
var_dump($keys, $values);
var_dump(array_combine($keys, $values));
After that you can simply build that into a query. However, it seems like your data might be user-provided so you should be very wary of that data. You seem to be almost introducing a SQL injection vulnerability in your code.
I suggest checking the $keys array against a whitelist and after that properly escaping all $values before using any of this in a query. You may find some info here: PDO with INSERT INTO through prepared statements
You can use preg_split.
$output = preg_split( "/ (,|:) /", $input );
Next, you can do a check in a loop.
foreach ($output as $value)
{
if(is_number($value))
$keys[] = $value;
else
$values[] = $value;
}
Since the string is close to json format i think making it a true json and decode it means no looping or exploding is an efficient solution.
$d1 = "a:1,b:2,c:3,d:4";
$d1 = "{\"".str_replace(array(",",":"),array('","','":"'), $d1)."\"}";
$arr = json_decode($d1, true);
$table = array_keys($arr);
$values = array_values($arr);
Var_dump($table);
Var_dump($values);
https://3v4l.org/Yqrbe
Edit; if you need the string you named as expected result use this:
$str ="Insert into Table1 (". Implode(",", $table) .") values (" . Implode(",", $values).")";
Echo $str;
Used below code.
Just little bit changes in your code this is working fine.
$d1 = "a:1,b:2,c:3,d:4"; //field number variable.. sometimes 4 or 10
$d2 = explode(',', $d1);
$colums = $values = array();
foreach ($d2 as $key => $value) {
$arr1 = explode(':',$value);
$colums[] = "`".$arr1[0]."`";
$values[] = "'".$arr1[1]."'";
}
$sql = 'insert into `Table1` ('.implode(",",$colums).') values ('.implode(",",$values).')';
Try with following logic:
foreach ($d2 as $key => $value) {
$arr1 = explode(':', $value);
if (count($arr1) == 2){
$arr[$arr1[0]] = $arr1[1];
}
}
Get all fields and values as comma separated:
$fields = array_keys($arr);
¢values = array_values($arr);
And use these variables into your query:
$fields = implode(",", array_keys($arr));
$values = implode(",", array_values($arr));
$query = "INSERT INTO Table1 (".$fields.") VALUES (".$values.")";
Running snipet: https://ideone.com/EXAPOt

Make all the strings of a string array into lower case except for the first word

Supposing I have an array Tomat, Ost
How can I accomplish so it is like this: Tomat, ost?
$ingredient_a = Array('Tomat', 'Ost');
echo implode(', ', $ingredient_a);
Use ucfirst and array_map with strtolower
echo ucfirst(implode(', ', array_map('strtolower',$ingredient_a)));
$ingredient_a = array('Tomat', 'Ost');
$new = array();
foreach($ingredient_a as $key => $value) {
$key == 0 ? $new[] = $value : $new[] = strtolower($value);
}
echo implode(', ', $new);

String to associative array

I'm having trouble using preg_match_all to split a string into key value pairs. An example of my string:
"%Title:Movie%Sortable%Writer:%Indexed:false%"
Where I expect results like:
$result['Title'] = 'Movie';
$result['Sortable'] = '';
$result['Writer'] = '';
$result['Indexed'] = 'false';
I can split the string using preg_match('/%/',$str,-1,PREG_SPLIT_NO_EMPTY); but it returns an indexed array. I need an associative array so that order is not important and I can use the key in a switch statement. What would be the correct regex to use in preg_match_all?
Try with:
$input = "%Title:Movie%Sortable%Writer:%Indexed:false%";
$output = array();
$data = explode('%', $input);
foreach ($data as $item) {
list($key, $value) = explode(':', $item);
$output[$key] = $value;
}
<?php
$arr = array();
$string = "%Title:Movie%Sortable%Writer:%Indexed:false%";
$d = explode('%', $string);
foreach($d as $item){
list($key,$value) = explode(':', $item);
$arr[$key] = $value;
}
print_r($arr);
?>

Split of data in PHP object

In the following code, is it possible to spilt the Object $author where white space occurs ?
<?php
$url="http://search.twitter.com/search.rss?q=laugh";
$twitter_xml = simplexml_load_file($url);
foreach ($twitter_xml->channel->item as $key) {
$a = $key->{"author"};
echo $a;
}
?>
$split = explode(' ', (string) $key->{"author"}));
OR
$split = preg_split('/\s+/', (string) $key->{"author"}));
To split by # just take $split and run in loop
foreach($split as $key => $value) {
$eta = explode('#', $value);
var_dump($eta);
}
To check if string exist use strpos
foreach($split as $key => $value) {
if (strpos($value, '#') !== 0) echo 'found';
}
Use explode:
$array = explode(' ', $key->{"author"});
There is an explode function that can easily accomplish that. So, for example:
$a = $key->{"author"};
$author = explode(" ", $a);
$first_name = $author[0];
$last_name = $author[1];
Hope that helps.
Assuming you merely care to get 2 parts: email, and "friendly name" (cause people have 1 to n number of names).
<?php
$url="http://search.twitter.com/search.rss?q=laugh";
$twitter_xml = simplexml_load_file($url);
foreach ($twitter_xml->channel->item as $key) {
$a = $key->{"author"};
preg_match("/([^ ]*) (.*)/", $a, $matches);
print_r($matches);
echo "\n";
}
?>

Categories