我有一个像:
这样的数组Array
(
[0] => Array
(
[kanal] => TV3+
[image] => 3Plus-Logo-v2.png
)
[1] => Array
(
[kanal] => 6\'eren
[image] => 6-eren.png
)
[2] => Array
(
[kanal] => 5\'eren
[image] => 5-eren.png
)
)
它可能扩展到几个子阵列。
如何制作如下列表:TV3+, 6'eren and 5'eren
?
答案 0 :(得分:4)
由于数组可能更深入,所以最好使用递归函数,例如array_walk_recursive()。
$result = array();
array_walk_recursive($inputArray, function($item, $key) use (&$result) {
array_push($result, $item['kanal']);
}
然后转换为逗号分隔的字符串,使用'和'分隔最后两个项目
$lastItem = array_pop($result);
$string = implode(',', $result);
$string .= ' and ' . $lastItem;
答案 1 :(得分:3)
花了一些时间,但我们走了,
$arr = array(array("kanal" => "TV3+"),array("kanal" => "5\'eren"),array("kanal" => "6\'eren"));
$arr = array_map(function($el){ return $el['kanal']; }, $arr);
$last = array_pop($arr);
echo $str = implode(', ',$arr) . " and ".$last;
<强> DEMO 强>
答案 2 :(得分:2)
你走了,
$myarray = array(
array(
'kanal' => 'TV3+',
'image' => '3Plus-Logo-v2.png'
),
array(
'kanal' => '6\'eren',
'image' => '6-eren.png'
),
array(
'kanal' => '5\'eren',
'image' => '5-eren.png'
),
);
foreach($myarray as $array){
$result_array[] = $array['kanal'];
}
$implode = implode(',',$result_array);
$keyword = preg_replace('/,([^,]*)$/', ' & \1', $implode);
echo $keyword;
答案 3 :(得分:2)
如果您只是将给定数组传递给implode()函数,则无法获得子数组的值。 see this example
假设您的数组名称为$ arr,代码位于
之下 $length = sizeof ( $arr );
$out = '';
for($i = 0; $i < $length - 1; $i ++) {
$out .= $arr [$i] ['kanal'] . ', ';
}
$out .= ' and ' . $arr [$length - 1] ['kanal'];
答案 4 :(得分:0)
我认为这对你有用:
$data = array(
0 =>['kanal' => 'TV1+'],
1 =>['kanal' => 'TV2+'],
2 =>['kanal' => 'TV3+'],
);
$output = '';
$size = sizeof($data)-1;
for($i=0; $i<=$size; $i++) {
$output .= ($size == $i && $i>=2) ? ' and ' : '';
$output .= $data[$i]['kanal'];
$output .= ($i<$size-1) ? ', ' : '';
}
echo $output;
//if one chanel:
// TV1
//if two chanel:
// TV1 and TV2
//if three chanel:
// TV1, TV2 and TV3
//if mote than three chanel:
// TV1, TV2, TV3, ... TV(N-1) and TV(N)
答案 5 :(得分:-1)
$last = array_slice($array, -1);
$first = join(', ', array_slice($array, 0, -1));
$both = array_filter(array_merge(array($first), $last));
echo join(' and ', $both);
代码是&#34;被盗&#34;从这里:Implode array with ", " and add "and " before last item
答案 6 :(得分:-1)
<?php
foreach($array as $arr)
{
echo ", ".$arr['kanal'];
}
?>