簡體   English   中英

比較 PHP 中對象的兩個 arrays 的最有效方法

[英]Most efficient way to compare two arrays of objects in PHP

我想比較 PHP 中的兩個對象 arrays。 但以最有效的方式。 我想知道array1中object的值是否存在於array2中的任何object中。 如果是這樣,我想得到它的ID。

我將值用於比較的數組如下所示:

array(2) {
  [0] =>
  class stdClass#529 (4) {
    public $value =>
    string(4) "Name"
    public $valueType =>
    string(4) "text"
    public $propertyName =>
    string(13) "beeforwhiskey"
    public $propertyType =>
    NULL
  }
  [1] =>
  class stdClass#530 (4) {
    public $value =>
    string(5) "Email"
    public $valueType =>
    string(4) "text"
    public $propertyName =>
    string(5) "email"
    public $propertyType =>
    string(4) "text"
  }
}

我想從中獲取 ID 的數組如下所示:

array(37) {
  [0] =>
  class stdClass#532 (9) {
    public $customFieldId =>
    string(5) "xyz"
    public $href =>
    string(50) "..."
    public $name =>
    string(7) "address"
    public $fieldType =>
    string(4) "text"
    public $format =>
    string(4) "text"
    public $valueType =>
    string(6) "string"
    public $type =>
    string(4) "text"
    public $hidden =>
    string(5) "false"
    public $values =>
    array(0) {
    }
  }
  [1] =>
  class stdClass#538 (9) {
    public $customFieldId =>
    string(5) "zyx"
    public $href =>
    string(50) "..."
    public $name =>
    string(3) "age"
    public $fieldType =>
    string(13) "single_select"
    public $format =>
    string(13) "single_select"
    public $valueType =>
    string(6) "string"
    public $type =>
    string(13) "single_select"
    public $hidden =>
    string(5) "false"
    public $values =>
    array(5) {
      [0] =>
      string(5) "18-29"
      [1] =>
      string(5) "30-44"
      [2] =>
      string(5) "45-59"
      [3] =>
      string(3) "60+"
      [4] =>
      string(3) "<18"
    }
  }
.
.
.

所以在這種情況下,我從array1中獲取每個object,檢查propertyName ,如果它存在於name字段中array2中的任何object中,那么我想從array2中獲取它的id

我用一些 foreach'es 做到了這一點,但我知道這不是最好的方法。 我怎樣才能讓它更短、更清晰、更少 memory 服用?

我不確定我是否使用了正確的列,因為這些值似乎不匹配,但我希望您可以根據需要更改它們。

這首先重新索引第二個數組,以便您要搜索的列是關聯數組的鍵,使用array_column()完成。 從那時起,您可以使用array1中的字段作為索引來訪問該數組。

我加了?? "Not found" ?? "Not found" ,如果你需要檢查這個,你也可以使用isset($array2[$element->propertyName])並做一些適當的事情。

// Index array2 by the 'name' value
$array2 = array_column($array2, null, "name");

foreach ( $array1 as $element)  {
    // Use the propertyName value from array1 to find details
    echo $array2[$element->propertyName]->customFieldId ?? "Not found".PHP_EOL;
}
$arr1 = [...]; // Your input array1
$arr2 = [...]; // Your input array2

$propertyNames = array_map(function ($o) {
    return $o->propertyName;
}, $arr1);

$res = array_map(function ($o) {
    return $o->customFieldId;
},
    array_filter($arr2, function ($o) use ($propertyNames) {
        return in_array($o->name, $propertyNames, true);
    })
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM