phparrays

Merge two flat arrays into a 2d array with predefined keys in each row


I want to achieve this kind of array using PHP.

[
  {
    "url": "https://url1.com",
    "code": "BNXl421s"
  },
  {
    "url": "https://url2.com",
    "code": "BNKpt1L2"
  },
  {
    "url": "https://url3.com",
    "code": "BMwhPRih"
  }
]

While i have these arrays :

$urls = 
  [
    "https://url1.com",
    "https://url2.com",
    "https://url3.com"
  ]

$codes= 
  [
    "BNXl421s",
    "BNKpt1L2",
    "BMwhPRih" 
  ]

I tried writing 2 foreach statements but it duplicates results since I had no idea how to achieve that.


Solution

  • Here, try this ( Or the demo here ):

    function merge($array1,$array2){
        $output = [];
        for($i = 0; $i < count($array1); $i++){
            $output[$array1[$i]] = $array2[$i];
        }
        return $output;
    }
    
    
    var_dump(merge($urls,$codes));
    

    This will output an array like this

    Array(
            "https://url1.com" => "BNXl421s",
            "https://url2.com" => "BNKpt1L2",
            "https://url3.com" => "BMwhPRih"
        )
    

    To make your direct wanted result, try this:


    function merge($array1,$array2){
        $output = [];
        for($i = 0; $i < count($array1); $i++){
            $output[] = array("url" => $array1[$i], "code" => $array2[$i]);
        }
        return $output;
    }
    var_dump(merge($urls,$codes));
    

    Same idea, but this output:

    array(3) {
      [0]=>
      array(2) {
        ["url"]=>
        string(16) "https://url1.com"
        ["code"]=>
        string(8) "BNXl421s"
      }
      [1]=>
      array(2) {
        ["url"]=>
        string(16) "https://url2.com"
        ["code"]=>
        string(8) "BNKpt1L2"
      }
      [2]=>
      array(2) {
        ["url"]=>
        string(16) "https://url3.com"
        ["code"]=>
        string(8) "BMwhPRih"
      }
    }
    

    Try it out here