how do I concatenate the string values of two arrays pairwise with PHP?

后端 未结 9 1305
傲寒
傲寒 2020-12-21 00:43

So I have two arrays

Array
(
[0] => test
[1] => test 1
[2] => test 2
[3] => test 3
)

and

Array
(
[0] => test         


        
相关标签:
9条回答
  • 2020-12-21 01:29

    If you have data coming from two different querys and they become two different arrays, combining them is not always an answer.

    There for when placed into an array ([]) they can be looped with a foreach to count how many, then looped together.

    Note: they must have the same amount in each array or one may finish before the other…..

    foreach ($monthlytarget as $value) {
    // find how many results there were
       $loopnumber++;
    }
    
    echo $loopnumber;
    
    for ($i = 0; $i < $loopnumber; $i++) {
    echo $shop[$i];
    echo " - ";
    echo $monthlytarget[$i];
    echo "<br>";
    }
    

    This will then display: -

    Tescos - 78
    Asda - 89
    Morrisons - 23
    Sainsburys - 46

    You can even add in the count number to show this list item number....

    0 讨论(0)
  • 2020-12-21 01:29

    There's no built-in function (that I know of) to accomplish that. Use a loop:

    $combined = array();
    for($i = 0, $l = min(count($a1), count($a2)); $i < $l; ++$i) {
      $combined[$i] = $a1[$i] . $a2[$i];
    }
    

    Adapt the loop to your liking: only concatenate the minimum number of elements, concatenate empty string if one of the arrays is shorter, etc.

    0 讨论(0)
  • 2020-12-21 01:30

    you loop through it to create a new array. There's no built-in function. Welcome to the wonderful world of programming :)

    Hints:

    • http://pt2.php.net/manual/en/control-structures.foreach.php
    • You can combine two strings with "."
    0 讨论(0)
提交回复
热议问题