Reputation: 19252
I have an array that looks like this.
'keyvals' =>
array
'key1' => 'value1'
'key2' => 'value2'
'key3' => 'value3'
Is there a cool way to flatten it to a string like 'value1 value2 value3'
? I also have access to PHP 5.3 if there's something new there.
Upvotes: 8
Views: 14585
Reputation: 1329
If you have to flatten this array to single-dimensional - take a look to this function (from Kohana fw)
/**
* Convert a multi-dimensional array into a single-dimensional array.
*
* $array = array('set' => array('one' => 'something'), 'two' => 'other');
*
* // Flatten the array
* $array = Arr::flatten($array);
*
* // The array will now be
* array('one' => 'something', 'two' => 'other');
*
* [!!] The keys of array values will be discarded.
*
* @param array array to flatten
* @return array
* @since 3.0.6
*/
function flatten($array)
{
$flat = array();
foreach ($array as $key => $value)
{
if (is_array($value))
{
$flat += flatten($value);
}
else
{
$flat[$key] = $value;
}
}
return $flat;
}
but if you just want to get a string - use native implode()
function
Upvotes: 3
Reputation: 111960
$someArray = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
implode(' ', $someArray); // => "value1 value2 value3"
Upvotes: 18