Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/284.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 mysql查询中如何合并两个数组_Php - Fatal编程技术网

Php mysql查询中如何合并两个数组

Php mysql查询中如何合并两个数组,php,Php,通过MySQL连接查询,我得到如下结果: Array ( [0] => c1 [1] => ot1 [2] => ot1 [3] => R ) Array ( [0] => 20 [1] => 10 [2] => 15 [3] => 5 ) c1 = [20] ot1 = [10,15] R = [5] 但我想要的结果是: Array ( [0] => c1 [1] => ot1 [2] => ot1 [3] => R

通过MySQL连接查询,我得到如下结果:

Array ( [0] => c1 [1] => ot1 [2] => ot1 [3] => R )
Array ( [0] => 20 [1] => 10 [2] => 15 [3] => 5 )
c1 = [20]
ot1 = [10,15]
R = [5]
但我想要的结果是:

Array ( [0] => c1 [1] => ot1 [2] => ot1 [3] => R )
Array ( [0] => 20 [1] => 10 [2] => 15 [3] => 5 )
c1 = [20]
ot1 = [10,15]
R = [5]
请帮帮我

假设

$array1 = array( 0 => 'c1', 1 => 'ot1', 2 => 'ot1' 3 => 'R' )
$array2 = array( 0 => 20, 1 => 10, 2 => 15, 3 => 5 )
试试这个:

 for($i = 0; $i < count($array1); $i++){

        if(!isset(${$array1[$i]}))
            ${$array1[$i]} = [];
        ${$array1[$i]}[] = $array2[$i];

    }
for($i=0;$i

请注意,仅当键是从0开始的连续整数且两个数组的维数相同时,此操作才有效,假设第一个数组名为
$array1
,另一个数组名为
$array2
,请尝试以下操作:

$merged = []; //new array for merged values
foreach ($array1 as $key => $value) { //iterate over the array which holds keys
    if (!isset($merged[$value])) { //if a key does not exist in new array yet
        $merged[$value] = []; //add it
    }
    $merged[$value][] = $array2[$key]; //add new value from the other array under this key
}
只要保留数组的完整性,就不会像另一个答案中那样对连续键有任何限制

用这个

$array1=数组('c1','ot1','ot1','R');
$array2=数组(20,10,15,5);
$array3=数组();
对于($i=0;$i
到目前为止您尝试了什么?
ot1=[10,15]
在这种情况下,如果数组键与“ot1”相同,则需要10,15才能让我们了解到您迄今为止尝试了什么,除了您提供的主代码之外,通过将其编辑到您的问题中而不是在注释中来自行解决它!。。。它被称为“显示努力”,是对付失败选民的良药。“分类审查”的结尾-->需要“努力”和“编辑”。FoeCH会删除限制一致的密钥,这只是我的一个老习惯,在密钥不被粗暴的情况下进行这样的迭代,但是您可以考虑使用PHP最佳实践改进代码——您没有PSR2、内联条件和变量,所有这些都被认为是不好的做法,我想这取决于你是如何习惯于读/写代码的。对我来说,这个版本看起来就像你不接受的攻击一样可读,它只是一条建议。我没有制定好的实践,我们都应该努力使代码遵循大多数程序员所接受的准则,这样就不取决于您如何习惯于读/写代码了。请将我的答案标记为正确答案。数组([0]=>20)数组([0]=>10)数组([0]=>10[1]=>15)数组([0]=>5);结果必须是:数组([0]=>20)数组([0]=>10[1]=>15)数组([0]=>5)听起来像是一个完全不同的问题,但到底是什么:
$arrayIndexed=Array\u值($merged)