如何在PHP中将多维关联数组转换为单维数组?

4

我有一个关于如何将多维数组转换为单维数组的快速查询

$teachers=array(array('post_id' => "John Doe",'video_id' => array('Government','English')), array('post_id' => "Steven Lee",'video_id' => array("Math","Science", "PE")),array('post_id' => "Jean Perot", 'video_id' => array("French", "Literature")));

https://dev59.com/Smoy5IYBdhLWcg3wWss_ - Wyck
1个回答

1
尝试这个。
function array_values_recursive($ary)  {
    $lst = array();
    foreach( array_keys($ary) as $k ) {
        $v = $ary[$k];
        if (is_scalar($v)) {
            $lst[] = $v;
        } elseif (is_array($v)) {
            $lst = array_merge($lst,array_values_recursive($v));
        }
    }
    return array_values(array_unique($lst)); // used array_value function for rekey
}

$teachers=array(
    array('post_id' => "John Doe",'video_id' => array('Government','English')), 
    array('post_id' => "Steven Lee",'video_id' => array("Math","Science", "PE")),
    array('post_id' => "Jean Perot", 'video_id' => array("French", "Literature")));

$flat = array_values_recursive($teachers);
print_r($flat); // OUTPUT : Array ( [0] => John Doe [1] => Government [2] => English [3] => Steven Lee [4] => Math [5] => Science [6] => PE [7] => Jean Perot [8] => French [9] => Literature )

非常感谢你的快速解决方案,这正是我们想要的完美解决方案。 - dhairya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接