PHP pour former chaîne comme « A, B, C et D » à partir des valeurs du tableau
-
28-10-2019 - |
Question
Étant donné le tableau suivant:
Array
(
[143] => Car #1
[144] => Car #2
[145] => Car #3
)
Je suis actuellement en utilisant ce
implode(', ', array_values($car_names))
pour générer une chaîne comme
Car # 1, # 2 voitures, voiture # 3
Je voudrais obtenir quelque chose comme en fait
Car # 1, # 2 voitures et voiture # 3
L'idée serait d'insérer « et » entre les deux derniers éléments du tableau.
Si le tableau arrive à contenir deux paires clé / valeur (par exemple, l'utilisateur dispose de 2 voitures), il n'y aurait pas des virgules.
Car # 1 et # 2 voitures
Et si le tableau contient une clé / valeur (par exemple, l'utilisateur a 1 voiture)
Car # 1
Toute suggestion comment y parvenir? J'ai essayé d'utiliser array_splice
mais je ne suis pas sûr que ce la voie à suivre (par exemple, l'insertion d'un nouvel élément dans le tableau).
Merci de nous aider!
La solution
I think you probably want something like this, using array_pop
to get the last element off the end of the array. You can then implode the rest of the array, and add the last element in a custom fashion:
$last_value = array_pop($car_names);
$output = implode(', ', array_values($car_names));
$output .= ($output ? ' and ' : '') . $last_value;
Edit: added conditional to check if the array had only one element.
Autres conseils
$last = array_pop($car_names);
echo implode(', ', $car_names) . ' AND ' . $last;
A preg_replace can look for the last command just just swap it to an and
$yourString = preg_replace( "/, ([\w#]*)$/", "and \1", $yourString );
This solution is a bit longer, but tested for all array sizes and it is a complete solution. Also, it doesn't modify the array like the above answers and is separated into a function.
function arrayToString($arr) {
$count = count($arr);
if ($count <= 2) {
return implode(' and ', $arr);
}
$result = '';
$i = 0;
foreach ($arr as $item) {
if ($i) $result .= ($i == $count - 1) ? ' and ' : ', ';
$result .= $item;
$i++;
}
return $result;
}
Compacted version with ugly formatting and ignoring good practices like initializing variables:
function arrayToString($arr) {
if (count($arr) <= 2) return implode(' and ', $arr);
foreach ($arr as $item) {
if ($i) $result .= ($i == count($arr) - 1) ? ' and ' : ', ';
$result .= $item; $i++;
}
return $result;
}
I'm not sure there's a built in function for this, but something like this should work.
$last = $car_names[count($car_names)-1];
$implodedString = implode(', ', array_values($car_names))
$implodedString = str_replace(", $last", "and $last", $implodedString);
That's an example with the functions named in my comment above:
strrpos()
- Find the position of the last occurrence of a substring in a stringsubstr()
- Return part of a string
and the code:
$text = implode(', ', array_values($car_names));
$last = strrpos($text, ',');
if ($last) $text = substr($text, 0, $last-1) . ' AND ' . substr($text, $last+1);
echo $text;
There are a number of ways you could do this. Here's another.
<?php
$cars = array('Car #1', 'Car #2', 'Car #3', 'Car #4');
$car = array('Car #1');
$twocars = array('Car #1', 'Car #2');
function arrayToText($arr) {
switch (count($arr)) {
case 1:
return $arr[0];
break;
case 2:
return implode($arr, ' and ');
break;
default:
$last = array_pop($arr);
return implode($arr, ', ') . ' and ' . $last;
break;
}
}
echo '<p>' . arrayToText($cars) . "</p>\n";
echo '<p>' . arrayToText($twocars) . "</p>\n";
echo '<p>' . arrayToText($car) . "</p>\n";
Output
<p>Car #1, Car #2, Car #3 and Array</p>
<p>Car #1 and Car #2</p>
<p>Car #1</p>