合并2个相同长度的数组项

时间:2018-07-24 16:19:06

标签: php arrays words

我有一个数组,其中包含一些单词以及其长度,就像这样:

Array
(
    [0] => Array
        (
            [word] => test
            [length] => 4
        )

    [1] => Array
        (
            [word] => sets
            [length] => 4
        )

    [2] => Array
        (
            [word] => foo
            [length] => 3
        )

)

我需要合并具有相同单词长度的数组项,例如,第一项的单词测试为4个字符,而第二项的单词集也为4个字符,因此应像这样合并:

Array
(
        [0] => Array
            (
            [word] => test, sets
            [length] => 4
        )

    [1] => Array
        (
            [word] => foo
            [length] => 3
        )

)

我在堆栈溢出附近看了一下,但是找不到解决方案。 如果有人有解决方案,这是我的代码,我真的很感激:

<?php
$words = array();
$length = array();
$words[] = array("word" => "test", "length" => '4');
$words[] = array("word" => "sets", "length" => '4');
$words[] = array("word" => "foo", "length" => '3');
echo '<pre>';
print_r($words);
echo '</pre>';

foreach($words as $key => $test){
    $length[$key] = $test['length'];
    if($test['length']==$length){
        echo 'hello';
    }
}

2 个答案:

答案 0 :(得分:0)

尝试一下。

<!DOCTYPE html>
<html style="margin: auto; display:table;">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript">
    </script>
    <script>var synth = window.speechSynthesis;</script>
    <!-- HTML5 Speech Recognition API -->
    <script>
            function startDictation() {
                document.getElementById('transcript').value = '';
                document.getElementById('output').value = '';
                if (window.hasOwnProperty('webkitSpeechRecognition')) {
                    var recognition = new webkitSpeechRecognition();
                    recognition.continuous = false;
                    recognition.interimResults = false;
                    recognition.lang = "en-US";
                    recognition.start();
                    recognition.onresult = function (e) {
                        window.alert(5 + 6);
                        document.getElementById('loader').hidden = false;
                        document.getElementById('transcript').value = e.results[0][0].transcript;
                        recognition.stop();
                        var data = e.results[0][0].transcript;
                        $.post("http://localhost:5000/news_urls", { "data": data },
                        function (response) {
                        document.getElementById('loader').hidden = true;
                            data = response;
                            document.getElementById("output").value = data["urls"];
                        }).error(function (response) {
                        document.getElementById('loader').hidden = true;
                            if (response.status == 400)
                                text = jQuery.parseJSON(response.responseText)["original_exception"];
                            else
                                text = "I'm sorry. I did not get that.";
                            document.getElementById("output").value = text;
                        });
                    };
                    recognition.onerror = function (e) {
                        recognition.stop();
                        console.log("Recognition had an error");
                        window.alert(10 + 6);
                    }
                }
            }

            function btnClick() {
	                synth.cancel();
                    var utterThis = new SpeechSynthesisUtterance(document.getElementById("output").value);
                    utterThis.voice = synth.getVoices()[0];
                    utterThis.pitch = 1.0;
                    utterThis.rate = 0.8;
                    utterThis.onerror = function(e) { console.log("Something went wrong with utterance."); };
                    synth.speak(utterThis);
            }
    </script>
    <style>
        .speech {
            border: 0px solid #DDD;
            width: 600px;
            padding: 0;
            margin: 0;
            font-family: "Calibri";
        }

            .speech input {
                border: 1;
                width: 240px;
                display: inline-block;
                height: 30px;
            }

            .speech img {
                float: right;
                width: 40px;
            }
    </style>
</head>

<body bgcolor="#e2e2e2">
    <h1 style="font-family: Calibri;">Delbot</h1>
    <div class="speech" ><i>It understands your voice commands, searches news and knowledge sources, and summarizes and reads out content to you.</i></div>
    <br /><i class="speech"><font color="gray">Only tested on Windows PCs. Not tested on other PCs or mobile devices.</font></i>

    <div class="speech">
            <textarea style="width: 600px;font-family: Calibri;font-size:x-large" name="q" id="transcript"
                      placeholder="Your query will appear here after you speak." rows="2" readonly="True"></textarea>
            <br>
            <input id="btn_query" type="button" onclick="startDictation()" value="Query"
                   style="font-family: Calibri;" />
            <img src="static/loader.gif" width="100px" align="left" style="float: left" hidden="True" id="loader" />
            <br><br>
            <h2 class="speech">Results</h2>
            <textarea style="width: 600px;font-family: Calibri;font-size:x-large" id="output" rows="2" placeholder="Results will appear here."
                      readonly="True"></textarea>
            <input id="btn_speak" type="button" value="Speak" onclick="btnClick()" style="font-family: Calibri;" />

    </div>
</body>
</html>

结果:

$words = array();
$length = array();

$words[] = array("word" => "test", "length" => '4');
$words[] = array("word" => "sets", "length" => '4');
$words[] = array("word" => "foo", "length" => '3');
foreach($words as $subword){
 $is_exist = false;
  foreach($length as &$sublength){
      if($subword["length"] == $sublength["length"]){
              array_push($sublength["word"],$subword["word"]);
              $is_exist = true;
      }

    } 

   if($is_exist == false){
       $new_arr=array("word" => array($subword["word"]), "length" => $subword["length"]);
       array_push($length,$new_arr);
    }

}

  //print $length
foreach($length as $sublength){

  foreach($sublength["word"] as $word){
      echo $word."-";

    }      
      echo ",".$sublength["length"];echo "<br>";
}

答案 1 :(得分:0)

好吧,我自己找到了一个解决方案。这是任何有兴趣找到解决方案的人的代码

$words = array();
$words[] = array("word" => "test", "length" => '4');
$words[] = array("word" => "sets", "length" => '4');
$words[] = array("word" => "foo", "length" => '3');
$new_array = array();
foreach($words as $key => $test){
    $length = $test['length'];
    if(isset($new_array[$length]['word'])){
        $new_array[$length]['word'] = $new_array[$length]['word'].', '.$test['word'];
    }else{
        $new_array[$length]['word'] = $test['word'];
        $new_array[$length]['length'] = $test['length'];
    }
}
print_r(array_values($new_array));

并输出:

Array
(
    [0] => Array
        (
            [word] => test, sets
            [length] => 4
        )

    [1] => Array
        (
            [word] => foo
            [length] => 3
        )

)