TWo数组长度不相等的数组组合

时间:2019-05-10 15:07:20

标签: php

我需要在php中结合使用两个数组。

我所拥有的:

numbers = array(1, 2,3,4,5,6);
letters = array('q', 'w', 'e', 'r');

我需要什么:

 1 q 
 2 w
 3 e
 4 r
 5 
 6

重要提示:我永远不会知道“数字”或“字母”数组包含多少个项目(只是长度永远不相等),这会因情况而异。

到目前为止,使我最接近目标,但这将所有字母都提交给每个数字:

   function array_combine2($arr1, $arr2) {
   return array_combine(array_intersect_key($arr1, $arr2), 
   array_intersect_key($arr2, $arr1));
   }
   foreach(array_combine2($number,$array) as $n1 => $a1)
   {
   echo $n1 . $a1."<br>";
    }

3 个答案:

答案 0 :(得分:4)

您获得了max并使用经典的for循环。检查元素isset是否使用空字符串。

$numbers = [1, 2,3,4,5,6];
$letters = ['q', 'w', 'e', 'r'];
$result = [];

for ($i = 0; $i < max(count($numbers), count($letters)); $i++) {
    $result[] = [
        "number" => isset( $numbers[$i] ) ? $numbers[$i] : "",
        "letter" => isset( $letters[$i] ) ? $letters[$i] : "",
    ];
}

echo json_encode( $result );

这将导致:

[
    {"number": 1,"letter": "q"}, 
    {"number": 2,"letter": "w"}, 
    {"number": 3,"letter": "e"}, 
    {"number": 4,"letter": "r"}, 
    {"number": 5,"letter": ""}, 
    {"number": 6,"letter": ""}
]

更新:如果只想echo个值,则可以:

$numbers = [1, 2,3,4,5,6];
$letters = ['q', 'w', 'e', 'r'];

for ($i = 0; $i < max(count($numbers), count($letters)); $i++) {
    echo isset( $numbers[$i] ) ? $numbers[$i] : "";
    echo " ";
    echo isset( $letters[$i] ) ? $letters[$i] : "";
    echo "<br />";
}

这将导致:

1 q
2 w
3 e
4 r
5
6 

答案 1 :(得分:2)

$numbers = [1, 2,3,4,5,6];  
$letters = ['q', 'w', 'e', 'r'];
$count = 0;
$combination = array();
foreach ($numbers as $num) 
{
    $val = '';
    if (isset ($letters[$count]))
    {
        $val = $letters[$count];
    }
    $combination += array($num => $val);    
    $count ++;
}

foreach($combination as $n => $l)
{
    echo $n . $l . "<br>";
}

答案 2 :(得分:2)

最短的解决方案

<?php
$numbers = array(1,2,3,4,5,6); 
$letters = array('q','w','e','r');
foreach($numbers as $key => $num) { 
    echo $num .' ';
    if (array_key_exists($key ,$letters)) // check if array element exists
    echo $letters[$key].'<br>';
    else echo "<br>";
}

说明。
首先,我们搜索数字数组或更长的数组,然后回显它的元素,同时检查字母数组中是否存在索引,如果存在,则使用数字回显该元素。