Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP如何在一个循环中合并两个数组_Php_Arrays_Merge - Fatal编程技术网

PHP如何在一个循环中合并两个数组

PHP如何在一个循环中合并两个数组,php,arrays,merge,Php,Arrays,Merge,我对下面的代码有问题,这让我发疯。我想做的是比较一个给定的数组和一个句子,然后我需要知道它们在句子中每次出现的位置,现在脚本只返回一个数组,例如在句子中找到名字Marta的位置。我试图将所有结果合并到一个数组中,但目前我有点不知所措。我希望有人能给我一些线索,使它。致以最良好的祝愿 $sentence = 'Maria is Maria and Marta is Marta.'; $womennames = array("Maria","Marta"); function poswom

我对下面的代码有问题,这让我发疯。我想做的是比较一个给定的数组和一个句子,然后我需要知道它们在句子中每次出现的位置,现在脚本只返回一个数组,例如在句子中找到名字Marta的位置。我试图将所有结果合并到一个数组中,但目前我有点不知所措。我希望有人能给我一些线索,使它。致以最良好的祝愿

$sentence = 'Maria is Maria and Marta is Marta.';
$womennames = array("Maria","Marta");    

function poswomen($chain, $words){

    foreach($words as $findme){
        $valida_existe = substr_count($chain,$findme);
        $largo_encuentra = strlen($findme);
        $posicion = array();

        for($x=0; $x < strlen($chain); $x++){
            $posic_x = strpos($chain, $findme, $x);
            if($posic_x >= 0){              
                $posicion[] = $posic_x;                    
                $x = $x+$largo_encuentra;
            }            
        }

        $posicion = array_unique($posicion);        
        $posicion = implode(",",$posicion);   

    }
    return $posicion;
}

poswomen($sentence, $womennames); 
print_r (poswomen($sentence, $womennames));
$句子='玛丽亚是玛丽亚,玛尔塔是玛尔塔';
$womennames=数组(“Maria”、“Marta”);
函数($chain,$words){
foreach($findme){
$valida_existe=substr_count($chain,$findme);
$largo_ENCUNTRA=strlen($findme);
$posicion=array();
对于($x=0;$x=0){
$posicion[]=$posic\u x;
$x=$x+$largo_ENCUNTRA;
}            
}
$posicion=array\u unique($posicion);
$posicion=内爆(“,”,$posicion);
}
返回$posicion;
}
poswomen($判刑,$womennames);
印刷品(poswomen($句子,$womennames));

正如barmar所说,您的位置不断重置,您需要将其设置在外部,然后添加当前找到的位置,以便继续。考虑这个例子:

$sentence = 'Maria is Maria and Marta is Marta.';
$women_names = array('Maria', 'Marta');
$pos = 0;
$positions = array();

foreach($women_names as $name) {
    while (($pos = strpos($sentence, $name, $pos))!== false) {
        $positions[$name][] = $pos;
        $pos += strlen($name);
    }
    $positions[$name] = implode(', ', $positions[$name]);
}

echo '<pre>';
print_r($positions);
echo '</pre>';

foreach
数组的每次迭代开始时,您都会重置
$posicion
。你应该在循环之外初始化它。谢谢Barmar,我不理解bucle的工作流程。对不起,我的意思是循环“bucle”是西班牙语…非常感谢Kevinabella,我真的很感谢你的帮助,它工作得很好;)
Array
(
    [Maria] => 0, 9
    [Marta] => 19, 28
)