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

Php 如何从数组元素中获取字符串的一部分,并将其插入到另一个数组中?,php,arrays,string,Php,Arrays,String,我有一个数组,它返回如下内容: [44] => 165,text:Where is this city:,photo:c157,correct:0,answers:[{text:Pery.,correct:true},{text:Cuba.,correct:false},{text:Brazil.,correct:false}]},{ 我想得到从字符串开始到数组元素值中第一次出现逗号的所有数字。在本例中,数字是165,我想将该数字作为关键问题ID放入另一个名为$newQuesitons的

我有一个数组,它返回如下内容:

[44] => 165,text:Where is this city:,photo:c157,correct:0,answers:[{text:Pery.,correct:true},{text:Cuba.,correct:false},{text:Brazil.,correct:false}]},{
我想得到从字符串开始到数组元素值中第一次出现逗号的所有数字。在本例中,数字是165,我想将该数字作为关键问题ID放入另一个名为$newQuesitons的数组中

下一部分将在第一次出现:之后获取字符串,直到下一次出现:为止,并将其添加到与关键问题相同的数组$newQuestions中

下一部分将是photo:,即我需要在photo之后获取字符串:直到下一次出现逗号,在本例中,提取的字符串将是c157


我想在$newQuestions数组中添加名为photo的新密钥,我想这可能会对您有所帮助

<?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);

?>       
我不完全理解输入的数组,所以上面的代码很可能需要调整,但至少它提供了一些逻辑


结果是:数组[165]=>数组[165]=>[text]=>这座城市在哪里[photo]=>c157[correct]=>0

我有自己的解决方案,至少对于问题的一部分。我使用以下代码设法获取questionID:

$newQuestions = array();

foreach ($arrQuestions as $key => $question) {
    $substring = substr($question, 0, strpos($question, ','));
        $newQuestions[]['questionID'] = $substring;  
}

我现在试着对问题部分做同样的事情。我将更新此代码,以防其他人可能有类似的任务要完成。

很高兴听到。您这样做是为了什么?我不知道如何搜索数组键值的一部分。如果您能告诉我如何获取从数组值开始到第一次出现逗号的所有数字,我想我可以从中找到解决方法关于正则表达式没有详细的介绍。之后,到这里:这是一个很好的学习工具,你想做什么。在那之后,你会感觉好得多,因为你学会了如何通过自己的优点来做这件事,而不是别人只是为你写出来。干杯。谢谢你的帮助,但我觉得在调整过程中我会迷失方向。我将尝试使用字符串操作的解决方案,我还将看到我可以从您的代码中使用什么。再次感谢。调整只是在输入上,我相信你正在使用2D数组进行输入。这段代码应该仍然可以工作,但在读取答案数组时可能会失败。不管怎么说,都要好好玩玩。我稍后会回来查看,看看你是如何理解的。我建议你删除这个,并把它放在你问的问题中,因为很可能会在那里看到它。