问题
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.
回答1:
$someArray = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
implode(' ', $someArray); // => "value1 value2 value3"
回答2:
See implode:
$flat = implode(' ', $array['keyvals']);
回答3:
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
来源:https://stackoverflow.com/questions/7941629/how-to-flatten-an-array-to-a-string-of-the-values