douhang8991
douhang8991
2017-06-23 13:47

php从数组元素中获取字符串并连接成新的数组元素

已采纳

I am trying to return array strings based on position, concatenate and append into a new array.

$matches = ([0] => 20170623 004129 982 a [4] => 20170623 004130 982 b [8] => 
            20170623 004130 982 b)
foreach ($matches as $match){
    $arr2 = explode(" ", $match);
    echo $arr2[0] . $arr2[1] . $arr2[2];

The for loop works for explode and can see each element(strings) of the array being separated into a new array $arr2, but each pass through the loop overwrites $arr2. My echo is returning the same result (the result of the last pass) multiple times. Looks like once for each pass.

Expected output, maybe something like:

$arr3 = ([0] => 20170623004129982 [1] => 20170623004130982 [3] => 
            20170623004130982)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dqdjfb2325 dqdjfb2325 4年前

    You need array_push()

    In your case

    <?php
        $arr2 = [];
        foreach ($matches as $match) {
            $values = explode(" ", $match);
            array_push($arr2, $values[0], $values[1], $values[2]);   
        }
    
        var_dump($arr2); // now $arr2 should contain all values
    ?>
    
    点赞 评论 复制链接分享
  • doufocheng6233 doufocheng6233 4年前

    create an array above foreach, so it will not reinitialize with each iteration as, and add the values in it which each iteration

    $arr=[];
    foreach ($matches as $match){
        $arr2 = explode(" ", $match);
        array_push($arr,array_map(function($arr2){
             return $arr2;
        },$arr2));
        echo "<pre>";print_r($arr);
    }
    
    点赞 评论 复制链接分享

相关推荐