我想把我的字符串(用逗号分隔)放在两个不同的数组中。
$str = 1,First,2,Second,3,Third,4,Forth,5,Fifth
我的目标是对数字和文字进行分组。
$number = {1,2,3,4,5)
$text = {first, second, third, forth, fifth}
我尝试使用explode()
,但我只能创建一个数组。
答案 0 :(得分:3)
<?php
$str = array(1,'First',2,'Second',3,'Third',4,'Forth',5,'Fifth');
$letters =array();
$no = array();
for($i=0;$i<count($str);$i++){
if($i%2 ==0){
$letters[] = $str[$i];
}else{
$no[] = $str[$i];
}
}
print_r($no);
print_r($letters);
?>
答案 1 :(得分:2)
可能这可以帮到你
$str = '1,First,2,Second,3,Third,4,Forth,5,Fifth';
$array = explode(',',$str);
$number = array();
$string = array();
foreach($array as $val)
{
if(is_numeric($val))
{
$number[] = $val;
}
elseif(!is_numeric($val))
{
$string[] = $val;
}
}
echo $commNum = implode(',',$number); // These are strings
echo '<br/>'.$commStr = implode(',',$string); // These are strings
echo '<pre>';
print_r($number); // These are arrays
echo '<pre>';
print_r($string); // These are arrays
答案 2 :(得分:1)
您可以使用explode
,但在这种情况下需要应用一些过滤器is_numeric
:
<?php
$str = '1,First,2,Second,3,Third,4,Forth,5,Fifth, erewwrw , 6 ';
$array = explode(',', $str);
$array_numbers = array();
$array_letters = array();
for($i = 0; $i < count($array); $i++) {
if(is_numeric(trim($array[$i]))) {
$array_numbers[] = trim($array[$i]);
} else {
$array_letters[] = trim($array[$i]);
}
}
print_r($array_numbers);
print_r($array_letters);
?>
输出:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Array
(
[0] => First
[1] => Second
[2] => Third
[3] => Forth
[4] => Fifth
)
答案 3 :(得分:1)
假设您的字符串包含数字后跟字符串,依此类推,
以下应该是解决方案。
创建两个空白数组:$numbers
和$strings
。
只需遍历数组并获得偶数和奇数元素。
偶数元素应该转到数字数组,奇数元素应该转到字符串数组。
$str = '1,First,2,Second,3,Third,4,Forth,5,Fifth';
$numbers = array();
$strings = array();
$temp = explode(',', $str);
$i=0;
foreach ($temp as $e) {
if ($i%2) {
$strings[] = $e;
}
else {
$numbers[] = $e;
}
++$i;
}
echo '<pre>';
print_r($numbers);
echo '</pre>';
echo '<pre>';
print_r($strings);
echo '</pre>';