PHP从数组中删除多余的数组

发布于 2024-10-08 15:30:44 字数 273 浏览 0 评论 0原文

这里有点脑残,我有一个看起来像这样的数组:

Array ( 
[0] => Array ( 'fruit' => 'orange', ) 
[1] => Array ( 'fruit' => 'apple', )
)

annnnnnnnd 它最终必须像这样:

Array ( 
[0] => 'orange'
[1] => 'apple' 
)

我该怎么做?

Having a bit of a brainfart here, I've got an array that looks like this:

Array ( 
[0] => Array ( 'fruit' => 'orange', ) 
[1] => Array ( 'fruit' => 'apple', )
)

annnnnnnnd it's got to end up like this:

Array ( 
[0] => 'orange'
[1] => 'apple' 
)

How do I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ぃ双果 2024-10-15 15:30:44

您可以使用 array_maparray_shift

$array = array_map('array_shift', $array);

或者只是循环它:

foreach($array as $key=>$value) {
    $array[$key] = array_shift($value);
}

更新:如果你总是想获取第一个值或者子数组只包含一个值,那么使用array_shift会更好......

如果你有更复杂的结构,例如更多子数组中的元素,那么您基本上想要展平数组

You can use array_map and array_shift

$array = array_map('array_shift', $array);

or just loop over it:

foreach($array as $key=>$value) {
    $array[$key] = array_shift($value);
}

Update: Using array_shift is much better if you always want to get the first value or if the subarrays contain only one value anyway...

If you have a more complicated structure, e.g. more elements in the subarrays, then you basically want to flatten your array.

氛圍 2024-10-15 15:30:44

如果密钥并不总是相同(即,如果它不总是水果),您可以这样做:

<?php
$source = array( 
    0 => array ( 'fruit' => 'orange', ) 
    1 => array ( 'fruit' => 'apple', )
);     

$destination = array();

foreach($source as $source_array)
{
    foreach($source_array as $value)
    {
        $destination[] = $value;
    }
}
?>

If the key isn't always the same (i.e. if it isn't always fruit), you could do this:

<?php
$source = array( 
    0 => array ( 'fruit' => 'orange', ) 
    1 => array ( 'fruit' => 'apple', )
);     

$destination = array();

foreach($source as $source_array)
{
    foreach($source_array as $value)
    {
        $destination[] = $value;
    }
}
?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文