PHP:如何在另一个数组的索引中包含另一个数组的元素?

时间:2017-09-16 04:53:25

标签: php arrays

我有两个数组:

<div onclick="window.location = 'http://www.yoururl.com'">

有没有什么方法可以将第一个数组的元素放到第二个数组的索引中,产生以下结果:

array(3)
{  
   [0]=>
      string(1) "1"
   [1]=>
      string(1) "1"
   [2]=>
      string(1) "2"
}

array(3)
{  
   [0]=>
      string(1) "abc"
   [1]=>
      string(1) "def"
   [2]=>
      string(1) "ghi"
}

我怎样才能在PHP中执行此操作?提前致谢。

2 个答案:

答案 0 :(得分:0)

您可以使用&#34; array_combine&#34;为此目的的方法。 http://php.net/array-combine

但是,数组中不能有相同的多个索引

array(3)
{  
   [1]=> "abc"
   [1]=> "def"
   [2]=> "ghi"
}

你有索引&#34; 1&#34;阵列两次。所以&#34; def&#34;将取代&#34; abc&#34;在你的数组中

答案 1 :(得分:0)

由于预期输出是不可能的,所以最好的做法是制作一个多维数组,其中问题id是答案的子数组。

$arr1 = [1,1,2];
$arr2 = ["abc","def","ghi"];

Foreach($arr1 as $key => $id){
    $threads[$id][] = $arr2[$key];
}

Var_dump($threads)

输出:

array(2) {
  [1]=>
     array(2) {
       [0]=> "abc"
       [1]=> "def"
     }
  [2]=>
     array(1) {
       [0]=> "ghi"
     }
}

https://3v4l.org/qpJDA

相关问题