douxie5176 2016-09-21 12:12
浏览 99

如何从数组元素中获取字符串的一部分,并将其插入另一个数组?

I have an array which returns something like this:

[44] => 165,text:Where is this city:,photo:c157,correct:0,answers:[{text:Pery.,correct:true},{text:Cuba.,correct:false},{text:Brazil.,correct:false}]},{

I would like to get all the numbers from the beginning of the string until the first occurrence of a comma in the array element value. In this case that would be number 165 and I want to place that number in another array named $newQuesitons as key questionID

Next part will be to get the string after the first occurrence of : until the next occurrence of : and add it into the same array ($newQuestions) as key question.

Next part will be the photo:, that is I need to get the string after the photo: until the next occurrence of the comma, in this case peace of the string extracted will be c157.

I would like to add that as new key named photo in the array $newQuestions

  • 写回答

2条回答 默认 最新

  • douou6807 2016-09-21 12:36
    关注

    I think this may be able to help you

    <?php
     $input =  '165,text:Where is this city:,photo:c157,correct:0';
    
    //define our new array
    $newQuestions = Array();
    //first part states we need to get all the numbers from the beginning of     the string until the first occurence of a ',' as this is our array key
    //$arrayKey[0] is our arrayKey
    $arrayKey = explode(',',$input);
    
    //second part requires us to loop through the array and split up the strings by comma and colon
    foreach($arrayKey as $data){
    //split each text into 2 by the colon
        $item = explode(':',$data);
        //we are only interested in items that have a colon in them, if we split it and the input has no colon, the count would be 0, so this check is used to ignore those
        if(count($item) > 0) {
            //now we can build our array
            $newQuestions[$arrayKey[0]][$item[0]] = $item[1];
        }
    
    }
    //output array
    print_r($newQuestions);
    
    ?>       
    

    I don't fully understand the inputted array so the code above will most likely have to be tweaked, but atleast it gives you some logic to go from.

    The output of this was: Array ( [165] => Array ( [165] => [text] => Where is this city [photo] => c157 [correct] => 0 ) )

    评论

报告相同问题?

悬赏问题

  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误