PHP在同一个键AND值上合并两个数组

时间:2016-05-20 09:28:09

标签: php arrays

我有两个数组。我想将它们合并到相同的键AND值上。如果它们具有相同的<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="fill" tools:context="com.example.asdf.MainActivity" > <WebView android:id="@+id/webView1" android:layout_width="match_parent" android:layout_height="match_parent" /> <ImageView android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:scaleType="fitXY" android:src="@drawable/bgg" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="22dp" android:layout_marginTop="22dp" android:gravity="center" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:text=" Factualnote is an web annotation application, which helps the users to mark the specific text, element, page, video, etc in a web page and share it to like-minded people.\r\n \r\nAs we know the relevant data has been wide-spreaded across various sites under many intentions, factualnote is a type of social software tool in which factual data are brought forward or narrow down to the web users." android:textColor="#ffffff" android:textSize="25sp" android:textStyle="normal|italic" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:orientation="vertical" > <EditText android:id="@+id/url" android:layout_width="290dp" android:layout_height="33dip" android:layout_above="@+id/button_show" android:layout_centerHorizontal="true" android:layout_gravity="center_horizontal" android:background="#ffffff" android:ems="17" android:hint="@string/edit_hint" android:radius="10dp" android:singleLine="true" android:text="http://www.zeptoh.com/lynked/sel.html" android:textColor="#000000" android:textSize="16sp" > <requestFocus /> </EditText> <Button android:id="@+id/button_show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:background="@drawable/blue_button" android:text="@string/button_title" android:textColor="#ffffff" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/undo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_weight="9" android:background="@drawable/blue_button2" android:text="@string/undo" android:textColor="#ffffff" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_weight="9" android:background="@drawable/blue_button2" android:text="Mark" android:textColor="#ffffff" /> <Button android:id="@+id/done" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_weight="10" android:background="@drawable/blue_button2" android:text="Generate" android:textColor="#ffffff" /> <Button android:id="@+id/redo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_weight="9" android:background="@drawable/blue_button2" android:text="@string/redo" android:textColor="#ffffff" /> </LinearLayout> </LinearLayout> <RelativeLayout android:layout_width="fill_parent" android:id="@+id/rl2" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" > <EditText android:id="@+id/name" android:layout_width="250dp" android:layout_height="33dip" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:background="#ffffff" android:ems="17" android:layout_gravity="center_horizontal" android:hint="Enter Title" android:singleLine="true" android:textColor="#000000" android:textSize="16sp" /> <EditText android:id="@+id/desc" android:layout_width="250dp" android:layout_height="33dip" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:background="#ffffff" android:ems="17" android:layout_gravity="center_horizontal" android:hint="Description about your note" android:singleLine="true" android:textColor="#000000" android:textSize="16sp" /> <TextView android:id="@+id/privateText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/desc" android:layout_below="@+id/desc" android:layout_marginTop="10dp" android:text="Private Note:" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="#ffffff" android:textSize="20sp" android:checked="true" android:buttonTint="@color/desing_color" android:textStyle="bold" /> <RadioGroup android:id="@+id/radioSex" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignTop="@+id/privateText" android:layout_toRightOf="@+id/privateText" android:orientation="horizontal" > <RadioButton android:id="@+id/yes" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="1dp" android:text="Yes" android:buttonTint="@color/desing_color" android:textColor="#ffffff" android:textSize="15sp" android:textStyle="bold" /> <RadioButton android:id="@+id/no" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@+id/privateText" android:layout_marginLeft="14dp" android:layout_toRightOf="@+id/yes" android:text="No" android:textColor="#ffffff" android:textSize="15sp" android:checked="true" android:buttonTint="@color/desing_color" android:textStyle="bold" /> </RadioGroup> <Button android:id="@+id/generate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:background="@drawable/blue_button" android:layout_below="@+id/radioSex" android:layout_marginTop="10dp" android:layout_marginLeft="70dp" android:textColor="#ffffff" android:text="Generate Note" /> <Button android:id="@+id/back" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_below="@+id/radioSex" android:background="@drawable/blue_button" android:layout_marginTop="10dp" android:layout_marginLeft="200dp" android:textColor="#ffffff" android:text="Back" /> </RelativeLayout> <ProgressBar android:id="@+id/progressBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> </RelativeLayout> ,那么它们将被合并。 ur_user_id仅为array2提供了一些额外数据,因此array1 = new_array.lengtharray1.length只需从array1获取其他数据。

array2

然后新数组必须如下所示。它将包含$array1 = array( array('ur_user_id'=> 1,'ur_fname'=>'PerA','ur_lname'=>'SonA'), array('ur_user_id'=> 2,'ur_fname'=>'PerB','ur_lname'=>'SonB'), array('ur_user_id'=> 3,'ur_fname'=>'PerC','ur_lname'=>'SonC'), ); $array2 = array( array('ur_user_id' => 5,'ur_code' => 'EE','ur_user_role' => 'testE'), array('ur_user_id' => 4,'ur_code' => 'DD','ur_user_role' => 'testD'), array('ur_user_id' => 6,'ur_code' => 'FF','ur_user_role' => 'testF'), array('ur_user_id' => 3,'ur_code' => 'CC','ur_user_role' => 'testC'), array('ur_user_id' => 1,'ur_code' => 'AA','ur_user_role' => 'testA'), array('ur_user_id' => 2,'ur_code' => 'BB','ur_user_role' => 'testB'), ); array1的值。

array2

$new_array = array( array('ur_user_id'=> 1,'ur_fname'=>'PerA','ur_lname'=>'SonA','ur_code' => 'AA','ur_user_role' => 'testA'), array('ur_user_id'=> 2,'ur_fname'=>'PerB','ur_lname'=>'SonB','ur_code' => 'BB','ur_user_role' => 'testB'), array('ur_user_id'=> 3,'ur_fname'=>'PerC','ur_lname'=>'SonC','ur_code' => 'CC','ur_user_role' => 'testC'), ); 始终小于或等于array1.length永远不会更大。并且两个数组的顺序不会总是有序。我已经尝试了下面的函数,我在这里的某个地方,但它对我不起作用,我对循环不太好。

array2.length

根据给定的数组,结果是这样的。它只合并在同一个密钥上。

function merge_common_keys(){
    $arr = func_get_args();
    $num = func_num_args();

    $keys = array();
    $i = 0;
    for ($i=0; $i<$num; ++$i){
        $keys = array_merge($keys, array_keys($arr[$i]));
    }
    $keys = array_unique($keys);

    $merged = array();

    foreach ($keys as $key){
        $merged[$key] = array();
        for($i=0; $i<$num; ++$i){
            $merged[$key][] = isset($arr[$i][$key]) ? $arr[$i][$key] : null;
        }
    }
    return $merged;
}

5 个答案:

答案 0 :(得分:1)

试试这个:

<?php

$array1 =    
    array(
        array('ur_user_id'=> 1,'ur_fname'=>'PerA','ur_lname'=>'SonA'),
        array('ur_user_id'=> 2,'ur_fname'=>'PerB','ur_lname'=>'SonB'),
        array('ur_user_id'=> 3,'ur_fname'=>'PerC','ur_lname'=>'SonC'),
    );
$array2 = 
    array(
        array('ur_user_id' => 5,'ur_code' => 'EE','ur_user_role' => 'testE'),
        array('ur_user_id' => 4,'ur_code' => 'DD','ur_user_role' => 'testD'),
        array('ur_user_id' => 6,'ur_code' => 'FF','ur_user_role' => 'testF'),
        array('ur_user_id' => 3,'ur_code' => 'CC','ur_user_role' => 'testC'),
        array('ur_user_id' => 1,'ur_code' => 'AA','ur_user_role' => 'testA'),
        array('ur_user_id' => 2,'ur_code' => 'BB','ur_user_role' => 'testB'),
    );


$result = array();

$userIdsFromArray1 = array_column($array1, 'ur_user_id');


foreach($array2 as $subarray)
{
    if(in_array($subarray['ur_user_id'], $userIdsFromArray1))
    {
        $result[] = array_merge($subarray, getDataFromArray1ByUserId($array1, $subarray['ur_user_id']));
    }
}


function getDataFromArray1ByUserId($array1, $userId)
{
    foreach($array1 as $key => $data)
    {
        if($data['ur_user_id'] == $userId)
            return $data;
    }

    return array();
}

 usort($result,function($a,$b){
    return strnatcmp($a['ur_user_id'],$b['ur_user_id']);
});

print_r($result);

工作示例:CLICK!

答案 1 :(得分:1)

在foreach循环中尝试这三行代码,如下所示:

$array1 =    
    array(
        array('ur_user_id'=> 1,'ur_fname'=>'PerA','ur_lname'=>'SonA'),
        array('ur_user_id'=> 2,'ur_fname'=>'PerB','ur_lname'=>'SonB'),
        array('ur_user_id'=> 3,'ur_fname'=>'PerC','ur_lname'=>'SonC'),
    );
$array2 = 
    array(
        array('ur_user_id' => 5,'ur_code' => 'EE','ur_user_role' => 'testE'),
        array('ur_user_id' => 4,'ur_code' => 'DD','ur_user_role' => 'testD'),
        array('ur_user_id' => 6,'ur_code' => 'FF','ur_user_role' => 'testF'),
        array('ur_user_id' => 3,'ur_code' => 'CC','ur_user_role' => 'testC'),
        array('ur_user_id' => 1,'ur_code' => 'AA','ur_user_role' => 'testA'),
        array('ur_user_id' => 2,'ur_code' => 'BB','ur_user_role' => 'testB'),
    );

$newArray =array(); 

foreach($array1 as $key => $val)
{
    $ids = array_map(function ($ar) {return $ar['ur_user_id'];}, $array2); //get the all the user ids from array 2
    $k = array_search($val['ur_user_id'],$ids); // find the key of user id in ids array
    $newArray[] = array_merge($array1[$key],$array2[$k]); /// merge the first array key with second
}   

echo "<pre>"; print_r($newArray);

这会给你:

(
    [0] => Array
        (
            [ur_user_id] => 1
            [ur_fname] => PerA
            [ur_lname] => SonA
            [ur_code] => AA
            [ur_user_role] => testA
        )

    [1] => Array
        (
            [ur_user_id] => 2
            [ur_fname] => PerB
            [ur_lname] => SonB
            [ur_code] => BB
            [ur_user_role] => testB
        )

    [2] => Array
        (
            [ur_user_id] => 3
            [ur_fname] => PerC
            [ur_lname] => SonC
            [ur_code] => CC
            [ur_user_role] => testC
        )

)

<强> LIVE DEMO

答案 2 :(得分:1)

当您需要反复检查/搜索值(实际上是唯一的标识符)时,效果最好的方法通常是:

  1. 生成键控数组并
  2. 反复调用isset()(而不是in_array()array_search()

ur_user_id是您的“唯一标识符”。
通过使用$array2ur_user_id的值分配为键来准备array_column()
$array1控制迭代次数。
我的方法将在使用联合运算符($array1)附加{{1之前,检查$array2+=之间的对应行(以避免 Notices )(避免出现 Notices )。 }}数据存储到$array2的每个原始行。
foreach循环中的$array1“通过引用修改”-这表示正在使用 actual 输入数组“处理”,而不是输入数组的副本

代码:(Demo

&

输出:

$array1 =    
    array(
        array('ur_user_id'=> 1,'ur_fname'=>'PerA','ur_lname'=>'SonA'),
        array('ur_user_id'=> 2,'ur_fname'=>'PerB','ur_lname'=>'SonB'),
        array('ur_user_id'=> 3,'ur_fname'=>'PerC','ur_lname'=>'SonC'),
    );
$array2 = 
    array(
        array('ur_user_id' => 5,'ur_code' => 'EE','ur_user_role' => 'testE'),
        array('ur_user_id' => 4,'ur_code' => 'DD','ur_user_role' => 'testD'),
        array('ur_user_id' => 6,'ur_code' => 'FF','ur_user_role' => 'testF'),
        array('ur_user_id' => 3,'ur_code' => 'CC','ur_user_role' => 'testC'),
        array('ur_user_id' => 1,'ur_code' => 'AA','ur_user_role' => 'testA'),
        array('ur_user_id' => 2,'ur_code' => 'BB','ur_user_role' => 'testB'),
    );  

$keyed = array_column($array2, NULL, 'ur_user_id'); // replace indexes with ur_user_id values

foreach ($array1 as &$row) {       // write directly to $array1 while iterating
    if (isset($keyed[$row['ur_user_id']])) { // check if shared key exists
        $row += $keyed[$row['ur_user_id']]; // append associative elements
    }
}

var_export($array1);

答案 3 :(得分:0)

尝试使用此代码,它可能对您有所帮助,它很简短而且没有遍历循环:

    usort($array2,function($a,$b){
        return strnatcmp($a['ur_user_id'],$b['ur_user_id']);
    });
    $array3 = array_replace_recursive($array1, $array2);

    $result = array_uintersect($array3,$array1,function($a,$b){
        return strnatcmp($a['ur_user_id'],$b['ur_user_id']);
    });
    print_r($result);

<强>输出

Array
(
    [0] => Array
        (
            [ur_user_id] => 1
            [ur_fname] => PerA
            [ur_lname] => SonA
            [ur_code] => AA
            [ur_user_role] => testA
        )

    [1] => Array
        (
            [ur_user_id] => 2
            [ur_fname] => PerB
            [ur_lname] => SonB
            [ur_code] => BB
            [ur_user_role] => testB
        )

    [2] => Array
        (
            [ur_user_id] => 3
            [ur_fname] => PerC
            [ur_lname] => SonC
            [ur_code] => CC
            [ur_user_role] => testC
        )

)

以下是Demo

答案 4 :(得分:-1)

你最好还是这样:

Working Example

$ids = array();
$out = array();
foreach($array1 as $key => $value){
    if(isset($array2[$key]))
        $out[$key][] = $array2[$key];
    $out[$key][] = $value;
    $ids[] = $array2[$key]['ur_user_id'];
}

foreach($array2 as $key => $val){
    if(!in_array($val['ur_user_id'], $ids))
        $out[$key][] = $array2[$key];
}