PHP如何根据字符串内容将字符串列表(数组)转换为嵌套数组

时间:2021-08-16 21:32:29

I have a list of strings with contain keywords.

我有一个包含关键字的字符串列表。

//random keywords random order
$array = array(
    'Keyword7 keyword4 keyword9 keyword1'
    'keyword4 keyword9 Keyword7 keyword2'
    'Keyword7 keyword4 keyword9 keyword3'
    'keyword3 keyword9 Keyword7 keyword5'

);

I would like to find a keyword/s which exists in all the strings "Keyword7" and Keyword9" and remove them. I would like to now set these keywords as the key of my new array.

我想找到一个关键字/ s,它存在于所有字符串“Keyword7”和Keyword9“中并删除它们。我现在想把这些关键字设置为我的新数组的关键字。

$new_array = array();
$new_array["Keyword7 Keyword9"] = array();

The value of this new array should now be the same strings but now they are missing the parent keyword/s.

这个新数组的值现在应该是相同的字符串,但现在它们缺少父关键字。

$new_array = array(
    'Keyword7 keyword9' =>array(
        array(
            ' keyword4 keyword1'
            ' keyword4 keyword2'
            ' keyword4 keyword3'
            ' keyword3 keyword5'
        );
    )
)

"keyword4" is the next match which has the most occurrences so this would go next. followed by the next best match "keyword3" or "keyword5".

“keyword4”是下一个匹配次数最多的匹配项,因此下次匹配。然后是下一个最佳匹配“keyword3”或“keyword5”。

$new_array = array(
    'Keyword7 keyword9' =>array(
        'keyword4' => array(
            'keyword1'
            'keyword2'
            'keyword3'
        ),
        'keyword3' =>array(
            'keyword5'
        )
    )
)

The following strings are all unique keywords the array is complete.

以下字符串都是数组完整的唯一关键字。

What ive done so far

到目前为止我做了什么

prepared the array

准备好阵列

    $keywordlist_array = array();

    foreach ($keywordlist as $key => &$string) {

        $new_str = trim(preg_replace('/\s+/', ' ',$string),' ');
        $arr = explode(' ', $new_str);
        asort($arr);

        $keys = array_values($arr);

        $keywordlist_array[$key] = array_combine($keys, array_fill_keys($keys, 0));

        $string = implode(' ', $arr);
    }

This removes any extra white space and orders the words alphabetically to make it easier for a comparison. I've also saves the array version of the string for later.

这将删除任何额外的空格并按字母顺序排序,以便于比较。我还保存了字符串的数组版本以供日后使用。

This loop counts the number of occurrences of each keyword across all stings, this does work but i Haven't managed to put it to any use.

这个循环计算所有stings中每个关键字的出现次数,这确实有效,但我没有设法把它用于任何用途。

    foreach ($keywordlist_array as $key_1 => $array_1) {

        foreach ($keywordlist_array as $key_2 => $array_2) {

            foreach (array_keys($array_1) as $keyword) {

                if(array_key_exists($keyword,$array_2)){

                    $keywordlist_array[$key_1][$keyword]++;
                }
            }
        }
    }

ive also created a function which does most of the work, but when it comes to an array with multiple parent keys i get stuck.

香港专业教育学院还创建了一个完成大部分工作的功能,但是当涉及到具有多个父键的数组时,我会陷入困境。

    function keywordListToNestedArray($keywordlist_array){

        $new_array = array();

        $length = count($keywordlist_array);

        $all_share_keywords = false;
        $some_share_keywords = false;


        $keywords  = array();

        $new_keywordlist_array = array();

        $max_values = array();


        foreach ($keywordlist_array as $key => $arr) {

            if(in_array($length, $arr)){

                $all_share_keywords = true;

                if(!$keywords){

                    foreach ($arr as $keyword => $value) {

                        if($value == $length){
                            $keywords[] = $keyword;
                        }
                    }
                }
                if($keywords){

                    $new_keywordlist_array[$key] = array_diff_key($arr, array_flip($keywords));
                }


            } else {



            }
        }

        if($all_share_keywords){

            $keyword = implode(' ', $keywords);
            $new_array[$keyword] = keywordListToNestedArray($new_keywordlist_array );

        } else if($some_share_keywords){

            // will have multiple new parents


        } else {

            //all values equal 1 (one occurance)

            foreach ($keywordlist_array as $key => $keywords) {

                $new_array[$key] = implode(' ', array_keys($keywords));
            }
        }

        return $new_array;
    }

    $new_array = keywordListToNestedArray($keywordlist_array);

Possible PHP functions which might help are similar_text() and levenshtein(),

可能有用的PHP函数是similar_text()和levenshtein(),

The question is "what would you do or how would you go about achieving this?". a full coded answer is not necessary, just need a little help getting started with this.

问题是“你会做什么或者你将如何实现这一目标?”。一个完整的编码答案是没有必要的,只需要一点帮助开始这个。

1 个解决方案

#1


0  

I had some free time so i gave it a shot. It's not perfect - but it does what you want. Maybe it will help you.

我有空闲时间所以我试了一下。它并不完美 - 但它可以满足您的需求。也许它会对你有所帮助。

Ex. output:

防爆。输出:

Array ( [keyword1 ] => Array ( [keyword2 ] => Array ( [keyword3 ] => Array ( [0] => keyword4 [1] => keyword5 [2] => keyword7 [3] => keyword6 [4] => keyword10 [5] => keyword9 [6] => keyword8 ) ) ) )

数组([keyword1] =>数组([keyword2] =>数组([keyword3] =>数组([0] => keyword4 [1] => keyword5 [2] => keyword7 [3] => keyword6 [4] => keyword10 [5] => keyword9 [6] => keyword8))))

<?php
        $keywords = array(
            'keyword1 keyword2 keyword3 keyword4',
            'keyword1 keyword2 keyword3 keyword5',
            'keyword1 keyword2 keyword7 keyword6',
            'keyword1 keyword10 keyword9 keyword8'
        );

        //create a new array with all the keywords
        $keywordArray = [];
        foreach($keywords as $keyword){
            $pieces = explode(" ", $keyword);
            foreach($pieces as $piece){
                $keywordArray[] = $piece;
            }
        }
        //count each keyword appearence
        $keywordCount = array_count_values($keywordArray);

        //create associative array key names
        $max = count($keywords);
        $newArray = [];
        while($max >= 0){
            $myStr = "";
            foreach($keywordCount as $key => $value){
                if($value == $max){
                    $myStr .= $key." ";
                }
            }
            if($myStr != ""){
                $newArray[$myStr] = $max;
            }
            $max--;
        }

        //get final array data
        end($newArray);
        $values = explode(" ", key($newArray));
        foreach($values as $value){
            if($value != ""){
                $finalArray[] = $value;
            }
        }
        unset($newArray[key($newArray)]);
        reset($newArray);

        //add previous key and final data to it
        end($newArray);
        $testArray[key($newArray)] = $finalArray;
        $rKey = key($newArray);
        unset($newArray[key($newArray)]);
        reset($finalArray);

        //repeat proccess from bottom to top
        while(!empty($newArray)){
            end($newArray);
            $testArray[key($newArray)] = $testArray;
            unset($newArray[key($newArray)]);
            unset($testArray[key($testArray)]);
            reset($newArray);
        }
        unset($testArray[$rKey]);

print_r($testArray);

?>

#1


0  

I had some free time so i gave it a shot. It's not perfect - but it does what you want. Maybe it will help you.

我有空闲时间所以我试了一下。它并不完美 - 但它可以满足您的需求。也许它会对你有所帮助。

Ex. output:

防爆。输出:

Array ( [keyword1 ] => Array ( [keyword2 ] => Array ( [keyword3 ] => Array ( [0] => keyword4 [1] => keyword5 [2] => keyword7 [3] => keyword6 [4] => keyword10 [5] => keyword9 [6] => keyword8 ) ) ) )

数组([keyword1] =>数组([keyword2] =>数组([keyword3] =>数组([0] => keyword4 [1] => keyword5 [2] => keyword7 [3] => keyword6 [4] => keyword10 [5] => keyword9 [6] => keyword8))))

<?php
        $keywords = array(
            'keyword1 keyword2 keyword3 keyword4',
            'keyword1 keyword2 keyword3 keyword5',
            'keyword1 keyword2 keyword7 keyword6',
            'keyword1 keyword10 keyword9 keyword8'
        );

        //create a new array with all the keywords
        $keywordArray = [];
        foreach($keywords as $keyword){
            $pieces = explode(" ", $keyword);
            foreach($pieces as $piece){
                $keywordArray[] = $piece;
            }
        }
        //count each keyword appearence
        $keywordCount = array_count_values($keywordArray);

        //create associative array key names
        $max = count($keywords);
        $newArray = [];
        while($max >= 0){
            $myStr = "";
            foreach($keywordCount as $key => $value){
                if($value == $max){
                    $myStr .= $key." ";
                }
            }
            if($myStr != ""){
                $newArray[$myStr] = $max;
            }
            $max--;
        }

        //get final array data
        end($newArray);
        $values = explode(" ", key($newArray));
        foreach($values as $value){
            if($value != ""){
                $finalArray[] = $value;
            }
        }
        unset($newArray[key($newArray)]);
        reset($newArray);

        //add previous key and final data to it
        end($newArray);
        $testArray[key($newArray)] = $finalArray;
        $rKey = key($newArray);
        unset($newArray[key($newArray)]);
        reset($finalArray);

        //repeat proccess from bottom to top
        while(!empty($newArray)){
            end($newArray);
            $testArray[key($newArray)] = $testArray;
            unset($newArray[key($newArray)]);
            unset($testArray[key($testArray)]);
            reset($newArray);
        }
        unset($testArray[$rKey]);

print_r($testArray);

?>