Array Exploding and matching per line / Using table Row - php

Hello can u give me the right code for this one...
$split_getCreatedfield = explode(",", "3,1,2");
$fieldsWithValue = explode("~","1->Samuel Pulta~2->21~3->Male~");
for($row=0;$row<count(fieldsWithValue);$row++){
$data = explode("->", $fieldsWithValue[$row]);
}
I want the output like this one
3 = 3 = Male
2 = 2 = 21
1 = 1 = Samuel Pulta

<?php
$split_getCreatedfield = explode(",", "3,1,2");
$fieldsWithValue = explode("~","1->Samuel Pulta~2->21~3->Male~");
$result = array();
foreach($fieldsWithValue as $key => $val){
if(trim($val) != ""){
$res = explode("->",$val);
$res_key = array_search($res[0],$split_getCreatedfield);
$result[$key][] = $split_getCreatedfield[$res_key];
$result[$key][] = $res[0];
$result[$key][] = $res[1];
}
}
krsort($result); /// Not really required
echo "<table>";
foreach($result as $vals){
echo "<tr><td>".$vals[0]."</td><td>=".$vals[1]."</td><td>=".$vals[2]."</td></tr>";
}
echo "</table>";
?>
output:
3 =3 =Male
2 =2 =21
1 =1 =Samuel Pulta

I would rather use preg_match_all(), like this:
$i = '3,2,1';
$s = '1->Samuel Pulta~2->21~3->Male~';
preg_match_all('/(\d+)->(.*?)(?:~|$)/', $s, $matches);
$fields = array_combine($matches[1], $matches[2]);
foreach (explode(',', $i) as $index) {
if (isset($fields[$index])) {
echo $index, ' = ', $index, ' = ', $fields[$index]. PHP_EOL;
}
}
The regular expression matches items like 1->Samuel Pulta and builds an array with the number as the key and whatever comes after it as the value.
Then, you simply iterate over the necessary indices and print their corresponding value from the $fields array.

Related

PHP Merge with separators

I am trying to merge two strings in a specific way.
Essentially I need to merge the first two strings into a third with a pipe symbol between them then separated by commas:
$merge1 = "id1,id2,id3"
$merge2 = "data1,data2,data3"
Those two would become:
$merged = "id1|data1,id2|data2,id3|data3"
I hope this makes sense?
I mean there is no PHP function that can output what you need.
Code produced desired output could be
<?php
$merge1 = "id1,id2,id3";
$merge2 = "data1,data2,data3";
$merged = [];
$arr1 = explode(',', $merge1);
$arr2 = explode(',', $merge2);
foreach ($arr1 as $key => $val) {
$merged[] = $val . '|' . $arr2[$key];
}
echo implode(',', $merged);
// id1|data1,id2|data2,id3|data3
This script will help you
<?php
$merge1 = "id1,id2,id3";
$merge2 = "data1,data2,data3";
$merge1 = explode(",", $merge1);
$merge2 = explode(",", $merge2);
$final = [];
foreach ($merge1 as $index => $value) {
$final[] = $value . "|" . $merge2[$index];
}
$final = implode(",", $final);
print_r($final);
output
id1|data1,id2|data2,id3|data3
Try this.
<?php
$merge1 = "id1,id2,id3";
$merge2 = "data1,data2,data3";
$merge1 = explode(",",$merge1);
$merge2 = explode(",",$merge2);
$mergeArr = array_combine($merge1,$merge2);
$mergeStr = [];
foreach($mergeArr as $k => $v) {
$mergeStr[] = $k.'|'.$v;
}
$mergeStr = implode(",",$mergeStr);
echo $mergeStr;
?>

How to check if a word is single or multi and to dived in 2 array in php

I have to check a array of string data .
For example this is the string :
$keywords="today, tomorroy, world, is a good day , a good day is, today"
I have to check if is single word or multi word.
If is multi word i have to order and leave only one for example : is a good day ; a good day is i have to leave only : is a good day . This words i have to store in other array.
In the end i have to have only this results:
This is my code:
$keywords = "";
$singleword="";
$multiword="";
foreach ($response->getResults() as $result) {
$keywords .= $result->getText()->getValue() . ",";
if(count(explode(' ', $keywords)) > 1) {
$multiword++;
}
$singleword++;
}
return $keywordsgenerated;
I need to return : today, tomorroy, world, is a good day
Please can you help me to fix , i'm new in php.
EDIT
I think you were looking for something like this:
<?php
$keywords="today, tomorrow, world, is a good day , a good day is, today";
$arr = array_unique(explode(",",$keywords));
$words = [];
foreach($arr as $key=>$a) {
$words_explode = explode(" ", $a);
foreach($words_explode as $w) {
$words[] = $w;
}
}
$new_words = array_unique($words);
$result = implode(" ", $new_words);
foreach($arr as $item) {
$result = str_replace($item,$item.",",$result);
}
$result = trim($result,", ");
var_dump($result);
UPDATE:
I think? I got what you were looking for?
$keywords = "hansgrohe,hansgrohe focus,küchenarmatur,hansgrohe metris";
$arr = explode(',', $keywords);
$already = [];
$result = '';
foreach($arr as $word) {
$subword = explode(" ", $word);
foreach($subword as $actual_word) {
if (!in_array($actual_word, $already)) {
$result .= $actual_word . ' ';
$already[] = $actual_word;
}
}
}
$result = rtrim($result);
//would result in hansgrohe focus küchenarmatur metris
echo $result;
UPDATE2:
If you want to know number of occurences of each word.
<?php
$keywords = "hansgrohe,hansgrohe focus,küchenarmatur,hansgrohe metris";
$arr = explode(",", $keywords);
$already = [];
$nrwords = [];
$result = '';
foreach($arr as $word) {
$subword = explode(" ", $word);
foreach($subword as $actual_word) {
if (!in_array($actual_word, $already)) {
$result .= $actual_word . ' ';
$already[] = $actual_word;
$nrwords[$actual_word] = 0;
}
$nrwords[$actual_word]++;
}
}
$result = rtrim($result);
//would result in hansgrohe focus küchenarmatur metris
echo $result;
//would show how many of each word that exists
echo '<pre>';
print_r($nrwords);
echo '</pre>';

PHP Array output with comma and "or" [duplicate]

This question already has answers here:
Implode an array with ", " and add "and " before the last item
(16 answers)
Closed 7 years ago.
My php output is an array. Like:
$array = array('banana', 'mango', 'apple');
Now If output is only 'Banana' then it will show simply
Banana
If output is 'banana' & 'mango' or 'apple' the i want to show like
Banana or Mango
If output is all.. then result will be shown
Banana, Mango or Apple
Now I can show result with comma using this code
echo implode(",<br/>", $array);
But How to add or ??
Please help.
Try this:
<?php
$array = array('banana','mango','apple');
$result = '';
$maxelt = count($array) - 1;
foreach($array as $n => $item) {
$result .= ( // Delimiter
($n < 1) ? '' : // 1st?
(($n >= $maxelt) ? ' or ' : ', ') // last or otherwise?
) . $item; // Item
}
echo $result;
use the count and map with that like
$count = count($your_array);
if($count > 3){
end($array); // move the internal pointer to the end of the array
$key = key($array); // fetches the key of the element pointed to by the internal pointer
$last = $your_array[$key];
unset($your_array[$key]);
echo implode(",<br/>", $your_array)."or"$last;
}
you can replace last occurrence of a string in php by this function:
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos !== false)
{
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
$array = array('banana', 'mango', 'apple');
$output = implode(", ", $array);
echo $output = str_lreplace(',',' or',$output);
$count = count($array);
if( $count == 1 ) {
echo $array[0];
} else if ( $count == 2 ) {
echo implode(' or ', $array);
} else if ( $count > 2 ) {
$last_value = array_pop( $array );
echo implode(', ', $array).' or '.$last_value;
}
please try below Code :
$array = array('banana','mango','apple');
$string = null;
if(count($array) > 1){
$string = implode(',',$array);
$pos = strrpos($string, ',');
$string = substr_replace($string, ' or ', $pos, strlen(','));
}elseif(count($array) == 1){
$string = $array[0];
}
echo $string;

Php sort by filename

I have this code
if($dateOrder){
$order = array(filemtime($filter_files[0]));
for($i=1;$i<$maxnr+1;$i++){
array_push($order,filemtime($filter_files[$i]));
}
array_multisort($order,SORT_DESC,SORT_NUMERIC,$filter_files,SORT_ASC,SORT_NUMERIC);
}
}
//end get image files
How to make possible sort order by filename? For example
picture1 , picture2 , picture3 picture10 , picture11
Here is the working code as per my proposal. The difference from your code is the usage of array_multisort method. PHP array_multiosrt expects single dimension non assoc arrays as its first and second dimension and then the whole data array as the last argument.
<?php
$dateOrder = true;
if($dateOrder){
/*$order = array(filemtime($filter_files[0]));
for($i=1; $i<$maxnr+1; $i++){
array_push($order,filemtime($filter_files[$i]));
}*/
$order = array('picture1', 'picture2', 'picture20', 'picture9', 'picture3', 'picture10', 'picture11');
//array_multisort($order,SORT_DESC,SORT_NUMERIC,$filter_files,SORT_ASC,SORT_NUMERIC);
$names = array();
for($i=0; $i<count($order); $i++) {
preg_match('/^(.+?)(\d+)$/', $order[$i], $matches);
$names[] = array($matches[1], $matches[2]);
}
$name = array();
$number = array();
foreach ($names as $key => $row) {
$name[$key] = $row[0];
$number[$key] = $row[1];
}
array_multisort($name, SORT_ASC, $number, SORT_NUMERIC, $names);
$output = array();
foreach ($names as $row) {
$output[] = $row[0] . $row[1];
}
print_r($output);
}
?>
Fiddle

How can i explode the string with , and |

How can i explode this? mars#email.com,123,12,1|art#hur.com,321,32,2
the output should be :
$email = mars#email.com
$score = 123
$street = 12
$rank = 1
then remove the |
$email = art#hur.com
$score = 321
$street = 32
$rank = 2
$string = mars#email.com,123,12,1|art#hur.com,321,32,2
explode( ',', $string );
is that correct?
foreach(explode('|', $str) as $v){
$data = explode(',',$v);
echo '$email = '.$data[0].
'$score = '.$data[1].
'$street = '.$data[2].
'$rank = '.$data[3];
}
You might want to use strtok() rather than explode().
http://www.php.net/manual/en/function.strtok.php
$arr = preg_split( '"[,|]"', 'mars#email.com,123,12,1|art#hur.com,321,32,2' );
$len = count($arr);
for( $i = 0; $i < $len; $i+=4 ) {
$email = $arr[$i];
$score = $arr[$i+1];
$street = $arr[$i+2];
$rank = $arr[$i+3];
}
you need to store the new array in variable >
$arr = explode(',',$string);
and I dont get what you want to do with the second part (after the |), but you can get the first par by doing this > $half = explode('|',$string)[0];
You need to unravel it in the right order:
first the blocks separated by |
then individual cells separated by ,
A concise way to do so is:
$array = array_map("str_getcsv", explode("|", $data));
Will give you a 2D array.
Use strtok and explode.
$tok = strtok($string, "|");
while ($tok !== false) {
list($email, $score, $street, $rank) = explode(',', $tok);
$tok = strtok(",");
}
I think what you want is something like this
$output = array();
foreach (explode('|', $string) as $person) {
$output[] = array(
'email' => $person[0],
'score' => $person[1],
'street' => $person[2],
'rank' => $person[3]
)
}
This stores all the results in a multidimensional array. For example, to print person 1's email, you'd use
echo $output[0]['email']; // mars#email.com
and to access person 2's street, you'd use
echo $output[1]['street']; // 32

Categories