在PHP中合并两个索引数组 [英] Merging two indexed arrays in php

查看:130
本文介绍了在PHP中合并两个索引数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个通过两个循环创建的索引数组:

I have two indexed arrays that have been created by 2 loops:

$个问题

Array ( 
    [10] => Yes 
    [11] => No 
    [12] => Yes 
    [13] => No 
    [14] => Yes 
    [15] => No 
)

$ comments

Array ( 
    [10] => comment 
    [11] => comment 
    [12] => comment 
    [13] => comment 
    [14] => comment 
    [15] => comment 
)

如何合并它们,以便获得以下结果并保留索引:

How do I combine them so I get the below result and preserve the indexing:

Array ( 
    [10] => Yes, comment 
    [11] => No, comment 
    [12] => Yes, comment 
    [13] => No, comment 
    [14] => Yes, comment 
    [15] => No, comment 
 )

查看array_merge,但是如果键相同,则追加.

Looked at array_merge but that appends if the key is the same.

如果输入数组具有相同的字符串键,则后一个值因为该密钥将覆盖前一个密钥.但是,如果数组包含数字键,以后的值将不会覆盖原始值值,但将被附加.

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

看了array_combine,但是:

Looked at array_combine but that:

使用keys数组中的值作为key和创建一个数组来自values数组的值作为对应的值.

Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.

我确定需要第三个循环来组合"它们,但是我该怎么做呢?

I'm sure I need a third loop to 'combine' them but how can I do that?

推荐答案

这应该为您提供一些选择.它合理地假设$ questions和$ comments之间的键是同步的,并处理是否有奇数键.

This should provide you with a couple of options. It makes the logical assumption that the keys between $questions and $comments are in sync, and handles if there are some odd ones.

<?php
$questions = array(
    '10' => 'Yes',
    '11' => 'No',
    '12' => 'Yes',
    '13' => 'No',
    '14' => 'Yes',
    '15' => 'No',
    '16' => 'No'
 );
$comments = array(
    '10' => 'comment 10',
    '11' => 'comment 11',
    '12' => 'comment 12',
    '13' => 'comment 13',
    '14' => 'comment 14',
    '15' => 'comment 15',
    '17' => 'comment 17'
 );

$combinedAsArray = array();
$combinedAsString = array();

foreach ($questions as $key => $value){

    if (array_key_exists($key, $comments)){
        $combinedAsArray[$key] = array($value, $comments[$key]);
        $combinedAsString[$key] = "$value, {$comments[$key]}";
    }else{
        $combinedAsArray[$key] = array($value, null);
        $combinedAsString[$key] = "$value, ";
    }
}

foreach ($comments as $key => $value){
    if (! array_key_exists($key, $questions)){
        $combinedAsArray[$key] = array(null, $value);
        $combinedAsString[$key] = " , $value";
    }
}

print_r($combinedAsArray);
print_r($combinedAsString);

这篇关于在PHP中合并两个索引数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆