I have a string and I would want to get the values/fields from it. However, the values are # separated.
Also, from one copy to the next it is comma separated.
As shown below;
$transaction = "
[2018-01-10 12:50:07.822#SAMUEL#TITUS],
[20120605152613#KEN#NAUGH],
[20120705152645#JOHHY#BRAVO]";
I need to loop through this string getting the values separated by the # for one record the to the next record separated by a comma.
The order of the fields is [TIME#FIRST_NAME#SECOND_NAME].
I can't think of a way to get this done.
Anyone?
Use explode to parse string into array
<?php
$transaction = "[2018-01-10 12:50:07.822#SAMUEL#TITUS],[20120605152613#KEN#NAUGH],[20120705152645#JOHHY#BRAVO]";
$parsed = explode(",", $transaction);
foreach($parsed as $val){
$val = explode("#", $val);
$first_name = $val[1];
$last_name = str_replace("]", '', $val[2]);
echo $first_name." ".$last_name."<br>"; // get firstname & lastname
}
?>
You can use the following solution using explode and array_map:
$transaction = "
[2018-01-10 12:50:07.822#SAMUEL#TITUS],
[20120605152613#KEN#NAUGH],
[20120705152645#JOHHY#BRAVO]";
//normalize the string and remove the unnecessary chars.
$transaction = str_replace(['[', ']', "\n"], '', $transaction);
//get all the rows as array.
$rows = explode(',', $transaction);
//create the columns in rows.
$row_arr = array_map(function ($row) {
return explode('#', $row);
}, $rows);
//info of the first row.
echo $row_arr[0][0]; // time
echo $row_arr[0][1]; // firstname
echo $row_arr[0][2]; // lastname
//run through the rows to output.
foreach ($row_arr as $row_item) {
echo 'Time: '.$row_item[0].', Firstname: '.$row_item[1].', Lastname: '.$row_item[2]."<br>";
}
demo: https://ideone.com/3uYcSw
Related
I have a list of strings like
$list = "foo, bar";
I use explode on this list to get the list items as an array:
$strings = explode(", ", $list);
Now I need to take each item of the array and pass it to an API one by one and the API will return the IDs for the list entries. I want to end up with a string that is just like $list but with the IDs instead of the strings.
My problem is that I can't pass an array to the API funtion. I need to do it for every single list item. So I'm looping through the array:
foreach($strings as $names){
$ID = $o_api->GetGroupIdsByName($s_token, $names)->getData();
$AssignedGroups = implode("", $ID).";";
echo $AssignedGroups;
}
If I run this code the result is: 3;4;
Which is exactly what I need to pass it to another API function. But when I need to re-use this list outside of the loop . If I then use $AssignedGroups I only get the last ID, not the 2 (or more) merged ones.
What am I doing wrong?
Here is the complete code for reference:
$Groups = explode(", ", $value["Groups"]);
//var_dump($Groups);
foreach($Groups as $Names){
$GroupIDs = $o_api->GetGroupIdsByName($s_token, $Names)->getData();
$AssignedGroups = implode("", $GroupIDs).";";
echo $AssignedGroups;
}
$o_api->CreateUser($s_token, $Login, $Password, $IsOfflineUser, $IsWindowsUser, $FirstName, $LastName, $AssignedGroups, $Ratings);
What really should be done here:
$Groups = explode(", ", $value["Groups"]);
//var_dump($Groups);
// init as empty array
$AssignedGroups = [];
foreach ($Groups as $Names) {
$GroupIDs = $o_api->GetGroupIdsByName($s_token, $Names)->getData();
// a new string to array
$AssignedGroups[] = implode(';', $GroupIDs);
}
// here you can implode again:
$AssignedGroups = implode(';', $AssignedGroups);
// or even with another delimiter
$AssignedGroups = implode(',', $AssignedGroups);
Fiddle with implode example.
I want to insert a new line after n commas.
For example I got this value: 385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426
How I could echo them all, but every 5th comma there should be a linebreak?
385,386,387,388,389,
390,391,392,393,394,
395,396,397,398,399,
400,401,402,403,404,
405,406,407,408,409,
410,411,412,413,414,
415,416,417,418,419,
420,421,422,423,424,
425,426
Here's one method:
// Get all numbers
$numbers = explode(',', $str);
// Split into groups of 5 (n)
$lines = array_chunk($numbers, 5);
// Format each line as comma delimited
$formattedLines = array_map(function ($row) { return implode(',', $row); }, $lines);
// Format groups into new lines with commas at the end of each line (except the last)
$output = implode(",\n", $formattedLines);
Try this
<?php
//Start //Add this code if your values in string like that
$string = "385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426";
$string_array = explode(',', $string);
//End //Add this code if your values in string like that
//If you have values in array then direct use below code skip above code and replace $string_array variable with yours
end($string_array);
$last = key($string_array);
foreach ($string_array as $key => $value) {
if($last==$key){
echo $value;
}else{
echo $value.',';
}
if(($key+1)%5==0){
echo "<br />";
}
}
?>
Try like this.
You can explode the string with commas and check for every 5th
position there should be a line break.
You can check it with dividing key with 5.(i.e) it will give you a
remainder of 0
Please note that key starts from 0, so I have added (key+1), to make it start from 1
$string = "385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426";
$stringexplode = explode(",", $string);
$countstringexplode = count($stringexplode);
foreach($stringexplode as $key => $val)
{
$keyIncrement = $key+1;
echo $val.($countstringexplode == $keyIncrement ? "" : ",") ;
if(($keyIncrement) % 5 == 0)
echo "<br>";
}
?>
How will i separated by comma the result of array_diff i tried this code but it gave me Warning: explode() expects parameter 2 to be string, array give
Warning: Invalid argument supplied for foreach()
<?php
$row['IMEI_MX'] = '123,222,333';
$row2["IMEI_MX"] = '123,222';
$imei = $row["IMEI_MX"];
$imeiserial = explode(',', $imei);
$imeitransfer = $row2["IMEI_MX"];
$imeitransferserial = explode(',', $imeitransfer);
$a1 = $imeiserial;
$a2 = $imeitransferserial;
$result = array_diff($a1,$a2);
$separate = implode(' ', $result);
foreach($separate as $is){
echo $is;
}
I think you just want to show the values of first string which are not in second string .
Tried this one
<?php
$row['IMEI_MX'] = '123,222,333,444';
$row2["IMEI_MX"] = '123,222';
$imei = $row["IMEI_MX"];
$imeiserial = explode(',', $imei);
$imeitransfer = $row2["IMEI_MX"];
$imeitransferserial = explode(',', $imeitransfer);
$a1 = $imeiserial;
$a2 = $imeitransferserial;
$result = array_diff($a1,$a2);
$sting = implode(',',$result);
echo $sting;
?>
It will result as
333,444
Use implode, it is the opposite function, you are using.
Use implode to get comma separated array values
$separate = implode(',', $result);
Explode is used for converting a string into array, while specifying the delimiter. Implode is the opposite one - you specify the glue for converting an array to string.
In your case, you don't need an explode after array_diff, because the result is itself an array. There's no need to convert anything. So, you just need to remove that line before the foreach:
foreach($result as $is){
echo $is;
}
When you use implode in the foreach, it throughs an error, because you're trying to loop through a string (the result of the implode operation) and the foreach operation expects an array.
UPDATE:
Follow the above code if you want to echo all items of the resulting array. If you want to display the array as a string, separated by comma, you need to go with implode but dismis the foreach after.
$separate = implode(',', $result);
echo $separate;
try this no need foreach just use implode
<?php
$row['IMEI_MX'] = '123,222,333,444';
$row2["IMEI_MX"] = '123,222';
$imei = $row["IMEI_MX"];
$imeiserial = explode(',', $imei);
$imeitransfer = $row2["IMEI_MX"];
$imeitransferserial = explode(',', $imeitransfer);
$a1 = $imeiserial;
$a2 = $imeitransferserial;
$result = array_diff($a1,$a2);
echo implode(',',$result);
?>
In my database table there is a column named 'marks' . it contains values like 50,55,67,88,...
Now I need to read this values one by one like - first 50, then 55 and so on. How is it possible using php ?
include("db_connect.php");
$result = mysql_query("SELECT * FROM students ",$con);
while($rows = mysql_fetch_array($result))
{
$mark1=$rows['marks'];//what will do here
$mark2=$rows['marks']; //should get value 55 and so on
}
If your values are comma separated then explode the field.
http://php.net/manual/en/function.explode.php
include("db_connect.php");
$result = mysql_query("SELECT * FROM students", $con);
while($rows = mysql_fetch_array($result)) {
$mark=explode(',', $rows['marks']);//what will do here
foreach($mark as $out) {
echo $out;
}
}
Explode the data from the database. Use the explode function.
Access using indexes
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
$mark1 = $exp[0]; //result is 50
$mark2 = $exp[1]; //result is 55
$mark3 = $exp[3]; //result is 67
}
Or loop using foreach
while($rows = mysql_fetch_array($result)) {
$marks = $row['marks']; //get value of marks from the database
$exp = explode("," , $marks); //explode marks data
foreach($exp as $mark) {
echo $mark;
}
}
If that row contains ,, the just use explode():
while($rows = mysql_fetch_assoc($result)) {
$mark1 = explode(',', $rows['marks']); // should contain the comma separated values
// in array form
// then loop again
foreach($mark1 as $mark_piece) {
// do something here
}
}
You should use the explode function
$marks = explode(",", $rows['marks']);
foreach($marks as $mark){
//your code to do something with the mark.
}
N.B. explode() function breaks the string into array, it accepts three arguments, first one is the delimiter that specifies where to break the string, second one is the string that needs splitting, and third one is not mandatory but it tells how many array to return.
$str_to_exploade = 'This,string,needs,some,exploiting';
$explode_string = explode(',', $str_to_exploade);
echo '<pre>';
print_r($explode_string);
echo $explode_string[0].'<br/>';
echo $explode_string[1];
More about explode() go to : http://php.net/manual/en/function.explode.php
i was writing this code to remove a list of values from a dynamic string key
//key
$chiave = "motore a scoppio di seconda generazione";
//sanitize string
//$chiave = pulisci($chiave);
//clean from double whitespaces
$chiave = preg_replace('/\s+/', ' ',$chiave);
//convert in lowercase
$chiave = strtolower($chiave);
//define array with all values to remove
$togliere = array("a","il","lo","la","egli","gli","li","di","do","e","รจ","alla","alle","&","un","uno","una");
$togliere2 = array("d'","l'");
//explode words
$keyval = explode(" ",$chiave);
//remove values
$keyvalclean = array_values(array_diff($keyval, $togliere));
//remove others values
$valori = array();
for($x=0; $x<=count($keyvalclean); $x++){
$valori[] = str_replace($togliere2,"",$keyvalclean[$x]);
}
//print the result
echo implode(" ",$valori);
this will output "motore scoppio seconda generazione"
there is a faster and optimized code to do that?
thanks
Your code looks okay to me. But you don't need to loop through the array to remove the values using str_replace(). This function can take an array as its argument and perform the replacement on each one of them in one go.
This:
$valori = array();
for($x=0; $x<=count($keyvalclean); $x++){
$valori[] = str_replace($togliere2,"",$keyvalclean[$x]);
}
can be changed to just:
$valori = str_replace($togliere2, "", $keyvalclean);
echo implode(" ",$valori);
Demo
Use str_replace()
You could insert an array to replaced by "" with this function.