array combine of unequal length of TWo arrays

前端 未结 3 1170
星月不相逢
星月不相逢 2021-01-20 15:45

I need help of combination of two arrays in php.

What I have:

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


        
相关标签:
3条回答
  • 2021-01-20 16:26
    $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>";
    }
    
    0 讨论(0)
  • 2021-01-20 16:30

    Shortest solution

    <?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>";
    }
    

    Explainaition.
    First we foreach the number array or the longer array, and we echo it's element, while doing that, we check if the index exists in the letters array, if it does then we echo that element with the number.

    0 讨论(0)
  • 2021-01-20 16:38

    You get the max and use the classic for loop. Check if element isset, if not, use an empty string.

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

    This will result to:

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

    Update: If you only want to echo the values, you can:

    $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 />";
    }
    

    This will result to:

    1 q
    2 w
    3 e
    4 r
    5
    6 
    
    0 讨论(0)
提交回复
热议问题