How to flatten an array to a string of the values?

橙三吉。 提交于 2021-02-19 01:56:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!