如何从现有数组创建新的 php 数组,其中数组值的前缀用于确定它是唯一的?

问题描述 投票:0回答:1

假设我有这个 php 数组:


$booklist =

Array
(
    [0] => Peppa / Season 2 / 43 The Quarrel / Page 1
    [1] => Nursery Rhymes / Wheels On The Bus / Page 1
    [2] => Wonderskills / Starter Book 2 / Unit 1 At The Firehouse / Part 3 / Page 3
    [3] => Oxford Phonics World / Level 2 Short Vowels / Unit 1 Short A / Page 7
    [4] => Peppa / Season 2 / 43 The Quarrel / Page 1
    [5] => Nursery Rhymes / Twinkle Twinkle / Page 1
    [6] => Wonderskills / Starter Book 2 / Unit 1 At The Firehouse / Part 2 / Page 17
    [7] => Oxford Phonics World / Level 1 The Alphabet / Unit 8 / Review W X Y Z / Page 2
    [8] => Peppa / Season 2 / 42 Granny And Grandpas Attic / Page 1
    [9] => Nursery Rhymes / The Phonics Song / Page 1
    [10] => Wonderskills / Starter Book 2 / Unit 1 At The Firehouse / Part 2 / Page 4
    [11] => Peter Pan / Level 1 / Page 1
    [12] => Peppa / Season 2 / 42 Granny And Grandpas Attic / Page 1
    [13] => Nursery Rhymes / The Phonics Song / Page 1
    [14] => Donald Duck / Page 19
    [15] => Donald Duck / Page 18
    [16] => Oxford Phonics World / Level 1 The Alphabet / Unit 8 / Letter Z / Page 2
)

如果新数组尚未包含具有初始前缀的项目(第一个“/”是分隔符),我想遍历每个项目并将其添加到新数组中。

最终数组将仅包含这些值:


$**finalArray **=

Array
(
    [0] => Peppa / Season 2 / 43 The Quarrel / Page 1
    [1] => Nursery Rhymes / Wheels On The Bus / Page 1
    [2] => Wonderskills / Starter Book 2 / Unit 1 At The Firehouse / Part 3 / Page 3
    [3] => Oxford Phonics World / Level 2 Short Vowels / Unit 1 Short A / Page 7
    [4] => Peter Pan / Level 1 / Page 1
    [5] => Donald Duck / Page 19

)

提前非常感谢。

我尝试了许多组合,例如 strpos() 和 str_starts_with() 与 array_push(),但我似乎无法让它工作。我要么得到相同的数组、一个空数组,要么得到一个包含数万个项目的数组。

$finalArray = [];

foreach ($booklist as $book){
    
            foreach($finalArray as $finalItem){
                
                $array = explode(" / ", $book);
                
                $mainBranch = $array[0];

                   if(0 === strpos($finalItem, $mainBranch){ /// problems in here
                     
                       array_push($finalArray, $book);

          }
    }
}

php arrays unique prefix
1个回答
0
投票

可以直接使用数组键进行过滤:

if(!isset($finalArray[$mainBranch])) {
    $finalArray[$mainBranch] = $book;
}

如果您确实需要最终数组为索引数组,请使用

array_values
进行转换:

$finalArray = array_values($finalArray);

顺便说一句,如果您只需要取斜杠之前的第一个单词,您应该使用

strstr
来避免创建数组:

$mainBranch = strstr($book, '/', true);
© www.soinside.com 2019 - 2024. All rights reserved.