【问题标题】:Join two associative arrays in PHP在 PHP 中加入两个关联数组
【发布时间】:2021-02-09 19:58:53
【问题描述】:

我有两个关联数组,一个叫做 $events,一个叫做 $wikipedia。
我想要一种有效的方法来将 $wikipedia 中的“extract”和“thumbnail”加入到 $events 中,其中 $events 中的“name”与 $wikipedia 中的“title”匹配。

原创 $events

$events = Array
(
    [0] => Array
        (
            [id] => 0
            [name] => Human
            [start] => 123
        )

    [1] => Array
        (
            [id] => 1
            [name] => Neanderthal
            [start] => 456
        )

    [2] => Array
        (
            [id] => 2
            [name] => Denisovan
            [start] => 456
        )

)

$维基百科

$wiki = Array
(
    [26685803] => Array
        (
            [pageid] => 26685803
            [ns] => 0
            [title] => Denisovan
            [thumbnail] => Array
                (
                    [source] => https://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/Denisova_4_Denisovan_molar_3.jpg/133px-Denisova_4_Denisovan_molar_3.jpg
                    [width] => 133
                    [height] => 200
                )

            [extract] => The Denisovans or Denisova hominins (  di-NEE-sə-və) are an extinct species or subspecies of archaic human that ranged across Asia during the Lower and Middle Paleolithic. Denisovans are known from few remains, and, consequently, most of what is known about them comes from DNA evidence. Pending consensus on their taxonomic status, they have been referred...
        )

    [682482] => Array
        (
            [pageid] => 682482
            [ns] => 0
            [title] => Human
            [thumbnail] => Array
                (
                    [source] => https://upload.wikimedia.org/wikipedia/commons/thumb/6/68/Akha_cropped_hires.JPG/119px-Akha_cropped_hires.JPG
                    [width] => 119
                    [height] => 200
                )

            [extract] => Humans (Homo sapiens) are a species of highly intelligent primates. They are the only extant members of the subtribe Hominina and—together with chimpanzees, gorillas, and orangutans—are part of the family Hominidae (the great apes, or hominids). Humans are terrestrial animals, characterized by their erect posture and bipedal locomotion; high manual...
        )

    [27298083] => Array
        (
            [pageid] => 27298083
            [ns] => 0
            [title] => Neanderthal
            [thumbnail] => Array
                (
                    [source] => https://upload.wikimedia.org/wikipedia/commons/thumb/d/d4/Range_of_NeanderthalsAColoured.png/200px-Range_of_NeanderthalsAColoured.png
                    [width] => 200
                    [height] => 95
                )

            [extract] => Neanderthals (, also Neandertals, Homo neanderthalensis or Homo sapiens neanderthalensis) are an extinct species or subspecies of archaic humans who lived in Eurasia until about 40,000 years ago. They most likely went extinct due to great climatic change, disease, or a combination of these factors.It is unclear when Neanderthals split from modern humans...
        )

)

使用来自 $wikipedia 的数据修改了 $events

$events = Array
(
    [0] => Array
        (
            [id] => 0
            [name] => Human
            [start] => 123
            [thumbnail] => Array
                (
                    [source] => https://upload.wikimedia.org/wikipedia/commons/thumb/6/68/Akha_cropped_hires.JPG/119px-Akha_cropped_hires.JPG
                    [width] => 119
                    [height] => 200
                )

            [extract] => Humans (Homo sapiens) are a species of highly intelligent primates. They are the only extant members of the subtribe Hominina and—together with chimpanzees, gorillas, and orangutans—are part of the family Hominidae (the great apes, or hominids). Humans are terrestrial animals, characterized by their erect posture and bipedal locomotion; high manual...
        )

    [1] => Array
        (
            [id] => 1
            [name] => Neanderthal
            [start] => 456
            [thumbnail] => Array
                (
                    [source] => https://upload.wikimedia.org/wikipedia/commons/thumb/d/d4/Range_of_NeanderthalsAColoured.png/200px-Range_of_NeanderthalsAColoured.png
                    [width] => 200
                    [height] => 95
                )

            [extract] => Neanderthals (, also Neandertals, Homo neanderthalensis or Homo sapiens neanderthalensis) are an extinct species or subspecies of archaic humans who lived in Eurasia until about 40,000 years ago. They most likely went extinct due to great climatic change, disease, or a combination of these factors.It is unclear when Neanderthals split from modern humans...
        )

    [2] => Array
        (
            [id] => 2
            [name] => Denisovan
            [start] => 456
            [thumbnail] => Array
                (
                    [source] => https://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/Denisova_4_Denisovan_molar_3.jpg/133px-Denisova_4_Denisovan_molar_3.jpg
                    [width] => 133
                    [height] => 200
                )

            [extract] => The Denisovans or Denisova hominins (  di-NEE-sə-və) are an extinct species or subspecies of archaic human that ranged across Asia during the Lower and Middle Paleolithic. Denisovans are known from few remains, and, consequently, most of what is known about them comes from DNA evidence. Pending consensus on their taxonomic status, they have been referred...
        )

)

我的尝试
我可以通过嵌套的 foreach 循环来实现这一点。然而,这似乎不是很有效,因为我必须迭代 $wikipedia 数组中的每个元素。我想知道是否有更好的方法。

    $arr = array();
    foreach($events as $event){
        foreach($wiki as $w){
            if ($w['title'] == $event['name']){
                $event['extract'] = $w['extract'];
                $event['thumbnail'] = $w['thumbnail'];
                array_push($arr, $event);
            }
        }
        
    }

【问题讨论】:

    标签: php associative-array


    【解决方案1】:

    重新映射有助于避免循环:

    $map = array_column($wiki, null, 'title'); # remap the array
    
    foreach ($events as ['id' => $id, 'name' => $name])
    {
        $events[$id]['extract']   = $map[$name]['extract'];
        $events[$id]['thumbnail'] = $map[$name]['thumbnail'];
    }
    

    【讨论】:

    • 很好的解决方案,谢谢!你介意解释一下 foreach AS 子句中发生了什么吗?我以前没见过你可以在那里放一个数组。
    • 它被称为数组销毁,在 PHP 7.1 中被添加为 list 函数 php.net/manual/de/… 的替代方法
    【解决方案2】:

    有一种更有效的方法。您的解决方案将具有 运行时。如果您需要加入多个项目,那就不太好。

    改进解决方案的最简单方法是通过创建一个以标题/名称为键的关联数组,预先从原始数据生成一个查找表。之后进行合并时,查找会很快(并且不会随着条目的增多而变慢)。

    你只循环两次而不是 n*m 次。这将导致线性运行时

    $lookup = [];
    $arr = [];
    foreach($events as $event){
       $lookup[$event['name']] = $event;
    }
    foreach($wiki as $w){
      $event = $lookup[$w['title']];
      if($event) {
         $event['extract'] = $w['extract'];
         $event['thumbnail'] = $w['thumbnail'];
         array_push($arr, $event);
      }
    }
    

    如果数据量很大,需要保留空间,可以将item的索引存储在查找表中,或者将数据添加到查找表后从原始数组中删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-04
      • 2012-05-03
      • 2017-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      相关资源
      最近更新 更多