简体   繁体   English

通过比较php中的值从两个数组数组制作数组

[英]Making array from two arrays arrays by comparing values in php

I want to create an array which would contain difference of two arrays and the difference is value not key.我想创建一个包含两个数组差异的数组,差异是值不是关键。

Array
(
    [0] => Creator
    [1] => HOD
)
Array
(
    [0] => Manager
    [1] => Creator
    [2] => HOD
)

I want manager as an output.我想要经理作为输出。 The sequence of arrays should not matter.数组的顺序应该无关紧要。

You can use array_diff()您可以使用array_diff()

In example :例如:

<?php 
$arr1 = array("creator", "hod");
$arr2 = array("manager", "creator", "hod");

$result = array_diff($arr2, $arr1);
//                       ^------^------ notice the order

var_dump($result);

Output输出

array (size=1)
  0 => string 'manager' (length=7)

This will result the elements of the first parameter that are not in the second.这将导致第一个参数的元素不在第二个参数中。


If you are doing :如果你正在做:

<?php 
$arr1 = array("creator", "hod");
$arr2 = array("manager", "creator", "hod");

$result = array_diff($arr1, $arr2);
//                       ^------^------ notice the order
var_dump($result);

Output输出

array (size=0)
  empty

Output is empty because there is no element in the first array that aren't in the second one.输出为空,因为第一个数组中没有第二个数组中没有的元素。


If you want to get both differences (the elements that are in first array and not in second and the elements that are in the second array and not in the first one), you can combine twice array_diff() and array_merge()如果你想获得这两个差异(这是第一个数组是第二阵列中,而不是在第一个元素,而不是在第二元素),你可以结合两次array_diff()array_merge()

In example :例如:

$arr1 = array("creator", "hod", "developper");
$arr2 = array("manager", "creator", "hod");

$result1 = array_diff($arr1, $arr2);
$result2 = array_diff($arr2, $arr1);

$result = array_merge($result1, $result2);

var_dump($result);

Output输出

array (size=2)
  0 => string 'developper' (length=10)
  1 => string 'manager' (length=7

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

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