如何在PHP中将这些单词与“?”结合起来?

时间:2021-12-28 21:37:16

I want to combine the [word] part of each array with " ", and the array structure is as follows:

我想将每个数组的[word]部分与“”结合起来,数组结构如下:

Array ( [0] => Array ( [word] => Hello [off] => 0 [len] => 5 [idf] => 4.0235948562622 [attr] => en ) [1] => Array ( [word] => , [off] => 5 [len] => 1 [idf] => 0 [attr] => un ) [2] => Array ( [word] => long [off] => 6 [len] => 4 [idf] => 3.465735912323 [attr] => en ) )

Array ( [0] => Array ( [word] => time [off] => 11 [len] => 4 [idf] => 3.465735912323 [attr] => en ) )

Array ( [0] => Array ( [word] => no [off] => 16 [len] => 2 [idf] => 1.7328679561615 [attr] => en ) )

Array ( [0] => Array ( [word] => see [off] => 19 [len] => 3 [idf] => 2.7465307712555 [attr] => en ) [1] => Array ( [word] => ! [off] => 22 [len] => 1 [idf] => 0 [attr] => un ) [2] => Array ( [word] => How [off] => 23 [len] => 3 [idf] => 2.7465307712555 [attr] => en ) )

Array ( [0] => Array ( [word] => are [off] => 27 [len] => 3 [idf] => 2.7465307712555 [attr] => en ) )

Array ( [0] => Array ( [word] => you [off] => 31 [len] => 3 [idf] => 2.7465307712555 [attr] => en ) )

Array ( [0] => Array ( [word] => recently [off] => 35 [len] => 8 [idf] => 5.1986036300659 [attr] => en ) [1] => Array ( [word] => ? [off] => 43 [len] => 1 [idf] => 0 [attr] => un ) )

Is there a built-in function of PHP that can do this? Because I think looping is less efficient.

是否有PHP的内置函数可以做到这一点?因为我认为循环效率较低。

2 个解决方案

#1


implode + array_map:

implode + array_map:

function func($a) {
    return $a['word'];
}
implode(' ', array_map('func', $x));

#2


Well, whatever happens, looping will take place, even if it is internal.

好吧,无论发生什么,循环都会发生,即使它是内部的。

You could use array_walk:

你可以使用array_walk:

$str = "";

function word_append($value, $key) { 

   global $str;

   $str .= $value['word'] . " ";

};

array_walk($func, $array_of_words);

$str should now contain the appended text.

$ str现在应该包含附加的文本。

#1


implode + array_map:

implode + array_map:

function func($a) {
    return $a['word'];
}
implode(' ', array_map('func', $x));

#2


Well, whatever happens, looping will take place, even if it is internal.

好吧,无论发生什么,循环都会发生,即使它是内部的。

You could use array_walk:

你可以使用array_walk:

$str = "";

function word_append($value, $key) { 

   global $str;

   $str .= $value['word'] . " ";

};

array_walk($func, $array_of_words);

$str should now contain the appended text.

$ str现在应该包含附加的文本。