tags:

views:

109

answers:

2

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

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.

+1  A: 

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

You could use 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.

Kazar
I'm confused whether you mean array_walk or array_map?
Shore
My apologies, that was a typo, I meant array_walk. Corrected in the answer.
Kazar
"looping will take place, even if it is internal."True, but the looping will probably be faster if it's internal.
Frank Farmer
+6  A: 

implode + array_map?

function func($a) {
   return $a['word'];
}
implode(' ', array_map('func', $x));
Jimmy
First parameter of `array_map` must be a string.
Gumbo
Does array_map not alter the original array?
Kazar
My apologies, appears it does not.
Kazar
In fact, this is better than my answer - +1
Kazar
@gumbo: good catch. fixed
Jimmy