F
F
FreezkoSS2018-02-08 19:03:57
PHP
FreezkoSS, 2018-02-08 19:03:57

How to remove comma in two dimensional array?

Here is the code guys, the bottom line is that I need to display cities for each region, while separating them with a comma, and where there is only one city, there should not be a comma at the end. Help plz, xs how to remove them.
<?php
echo " Displaying several regions and their cities starting with the letter 'K':
";
$city = array(
"Moscow Region" => array("Moscow", "Zelenograd", "Klin", "Mozhaysk"),
"Leningrad Region" => array("Saint Petersburg", "Peterhof", "Tikhvin ", "Podporozhye", "Kronstadt"),
"Ryazan region" => array("Ryazan", "Kasimov", "Ryazhsk", "Skopin",
"Murmansk region" => array("Murmansk", "Kirovsk", "Olenegorsk", "Snezhnogorsk", "Kovdor"),
"Leningrad region" => array("St. Petersburg", "Vsevolozhsk", "Gatchina" , "Ivangorod")
);
$city2 = array();
foreach ($city as $key => $value) {
echo "
", $key, ":
";
foreach ($value as $key => $value) {
if(mb_substr($value, 0, 1) == 'K') {
$city2 = $value.", ";
echo $city2;
}
}
}
Here is the result:
Moscow region:
Klin,
Kem,
Murmansk region:
Kirovsk, Kovdor,
And it should be like this:
Moscow region:
Klin
Leningrad region:
Ryazan region:
Kasimov
Republic of Karelia:
Kem
Murmansk region:
Kirovsk, Kovdor

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Majidov, 2018-02-08
@FreezkoSS

Filter ( array_filter()) the array with cities to start with the letter "K"
( ), and then convert the resulting array to a string, separating the values ​​with a comma :mb_substr($e, 0, 1) == 'К'', '

foreach ($city as $key => $value){
  echo $key . ': ' .  join(', ', array_filter($value, function($e){return mb_substr($e, 0, 1) == 'К'})) . '<br>';
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question