简体   繁体   English

将两个数组合并为一个数组(相同的键)

[英]Merge two arrays into one array (identic keys)

I think this is a very simple question, but can't figure out how to this. 我认为这是一个非常简单的问题,但无法解决该问题。 I've these two arrays: 我有两个数组:

(
    [0] => Array
    (
        [accordion_title] => [accordion-title]Title 1[/accordion-title]
    )
    [1] => Array
    (
        [accordion_title] => [accordion-title]Title 2[/accordion-title]
    )
)

(
    [0] => Array
    (
        [accordion_content] => [accordion-content]Content 1[/accordion-content]
    )
    [1] => Array
    (
        [accordion_content] => [accordion-content]Content 2[/accordion-content]
    )
)

How can I combine/merge them that they look like this? 如何合并/合并它们,使它们看起来像这样?

(
    [0] => Array
    (
        [accordion_title] => [accordion-title]Title 1[/accordion-title]
        [accordion_content] => [accordion-content]Content 1[/accordion-content]
    )
    [1] => Array
    (
        [accordion_title] => [accordion-title]Title 2[/accordion-title]
        [accordion_content] => [accordion-content]Content 2[/accordion-content]
    )
)

Thanks for your help. 谢谢你的帮助。

You can try in this way: 您可以通过以下方式尝试:

$array1 = array( array('accordion_title'=>'Title 1'),array('accordion_title'=>'Title 2') );
$array2 = array( array('accordion_content'=>'Content 1'),array('accordion_content'=>'Content 2') );

$array3 = array();
foreach( $array1 as $key => $array )
{
    $array3[] = array( key($array) => current($array), key($array2[$key]) => current($array2[$key]) );
}

print_r( $array3 );

This is the output: 这是输出:

Array
(
    [0] => Array
        (
            [accordion_title] => Title 1
            [accordion_content] => Content 1
        )

    [1] => Array
        (
            [accordion_title] => Title 2
            [accordion_content] => Content 2
        )

)

Updated: 更新:

With this function you can combine infinite arrays (not only two), even if they have different sizes: 使用此功能,您可以组合无限数组(不仅两个),即使它们具有不同的大小:

/*   Groups passed arrays in an array of associative arrays with same keys and values
 *
 *   @example          $array1 = array( array('a'=>'val1'),array('a'=>'val2') );
 *                     $array2 = array( array('b'=>'val3'),array('b'=>'val4') );
 *                     $array3 = array( array('c'=>'val5'),array(),array('c'=>'val6') );
 *                     multiArrayCombine( $array1, $array2, $array3 );
 *                     return: array
 *                     (
 *                        0 => array('a'=>'val1','b'=>'val3','c'=>'val5'),
 *                        1 => array('a'=>'val2','b'=>'val4'),
 *                        2 => array('c'=>'val6')
 *                     )
 *                     
 *   @param   array    $array1[, $array2[, $array3...]]
 *
 *   @option  const    T_OBJECT_CAST cast returned assoc arrays as stdObject
 *
 *   @return  array
 */
function multiArrayCombine()
{
    /* Get all passed parameters and T_OBJECT_CAST option: */
    $args     = func_get_args();
    $asObject = ( T_OBJECT_CAST == end($args) );
    if( $asObject ) array_pop( $args );

    $retval = array();          # Init array to be returned

    /* Retrieve highest passed arrays key: */
    $max = 0;
    foreach( $args as $array ) $max = max( $max, max( array_keys($array) ) );

    /* Loop for each arrays key: */
    for( $i=0; $i<=$max; $i++ )
    {
        /* Init associative array to add:  */
        $add = array();

        /* Process actual key ($i) of each passed array:  */
        foreach( $args as $array )
        {
            /* If the key ($i) exists, add  each passed array:  */
            if( isset($array[$i]) AND is_array($array[$i]) )
            {
                foreach( $array[$i] as $key => $val )
                { $add[$key] = $val; }
            }
        }

        /* Add the obtained associative array to return array */
        if( $asObject ) $retval[] = (object) $add;
        else            $retval[] = $add;
    }

    return $retval;
}

So, with the following code (three arrays): 因此,使用以下代码(三个数组):

$array1 = array( array('accordion_title'=>'Title 1'),array('accordion_title'=>'Title 2') );
$array2 = array( array('accordion_content'=>'Content 1'),array('accordion_content'=>'Content 2') );
$array3 = array( array('accordion_date'=>'Date 1'),array(),array('accordion_date'=>'Date 3') );

print_r( multiArrayCombine( $array1, $array2, $array3 ) );

the output is: 输出为:

Array
(
    [0] => Array
        (
            [accordion_title] => Title 1
            [accordion_content] => Content 1
            [accordion_date] => Date 1
        )

    [1] => Array
        (
            [accordion_title] => Title 2
            [accordion_content] => Content 2
        )

    [2] => Array
        (
            [accordion_date] => Date 3
        )
)

eval.in demo 评估演示

Updated 2: 更新2:

  1. Now the function return all passed values of each rows, not only the first; 现在,该函数返回每行的所有传递的值,而不仅仅是第一行;
  2. Added option T_OBJECT_CAST : passing constant T_OBJECT_CAST after the list of arrays, rows of returned array as formatted as stdObjects instead of arrays. 添加了选项T_OBJECT_CAST :在数组列表之后返回常量T_OBJECT_CAST ,返回的数组行格式化为stdObjects而不是数组。

Explanation: 说明:

To allow not predetermined arguments, I don't format function as multiArrayCombine( $arg1, $arg2, ... ) , I use instead the func_get_args() function, that "allow user-defined functions to accept variable-length argument lists". 为了不接受预定的参数,我不将函数格式化为multiArrayCombine( $arg1, $arg2, ... ) ,而是使用func_get_args()函数,即“允许用户定义的函数接受可变长度参数列表” 。

First of all (in the latest update), I check if the last argument is the predefined constant T_OBJECT_CAST : if it is, I set $asObject to True , then I pop-it off the end of arguments array; 首先(在最新更新中),我检查最后一个参数是否为预定义的常量T_OBJECT_CAST :如果是,则将$asObject设置$asObject True ,然后将其弹出参数数组的结尾; now in the $args variable I have an array with each passed arrays. 现在在$args变量中,每个传递的数组都有一个数组。

Next step: I retrieve the max key value of all passed arrays; 下一步:检索所有传递的数组的最大键值; i choose this way instead of more comfortable foreach( $array1 as $row ) to avoid to omit values if one of the other arrays have more rows than the first. 我选择这种方式,而不是更舒适的foreach( $array1 as $row )以避免在其他数组中的一个数组比第一个数组多的情况下忽略值。 Eventually not numeric keys are omitted. 最终,没有数字键被省略。

Then, the main loop: I process each row of originals arrays and I add their keys and values to row that will added to returned array. 然后是主循环:处理原始数组的每一行,并将其键和值添加到将添加到返回数组的行中。 If there are duplicated keys, only the last is returned. 如果键重复,则仅返回最后一个键。

After processing each array, i add the obtained row (converted to object if this option is passed) to returning array. 处理完每个数组后,我将获得的行(如果传递了此选项,则转换为对象)添加到返回的数组中。

That's all! 就这样!


Globish here, i'm sorry 抱歉,对不起

Something like this should work: 这样的事情应该起作用:

$merged = [];
$array1 = [ ... ];
$array2 = [ ... ];
foreach ($array1 as $key => $value) {
    $merged[$key][] = $value;
}
foreach ($array2 as $key => $value) {
    $merged[$key][] = $value;
}

I hope what I've done here makes sense. 我希望我在这里所做的一切有意义。

Maybe use the php function array array_merge($array1 ,$array2) 也许使用PHP函数array array_merge($array1 ,$array2)

http://php.net/manual/fr/function.array-merge.php http://php.net/manual/fr/function.array-merge.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM