dongzhao1930 2016-11-29 15:06
浏览 70
已采纳

PHP使用相同的键合并两个数组

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.

  • 写回答

4条回答 默认 最新

  • dongluanguang4774 2016-11-29 15:13
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 vscode的问题提问
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM