如何从PHP数组中删除键

16

我的数组是:

Array(
    2 => 'Title: Warmly little before cousin sussex entire set Blessing it ladyship.',
    3 => 'Snippet: Testing',
    4 => 'Category: Member',
    5 => 'Tags: little, before, entire',
)

我想要移除键2、3、4和5,使其变成这样:

Array(
    'Title: Warmly little before cousin sussex entire set Blessing it ladyship.',
    'Snippet: Testing',
    'Category: Member',
    'Tags: little before entire',
)

我的实际数组是:

    Array
    (
    [0] => Array
        (
            [0] => Array
                (
                    [chapter_id] => 7
                    [version_id] => 1
                    [chapter_number] => 1
                    [Topics] => Array
                        (
                            [0] => Array
                                (
                                    [topic_id] => 8
                                    [content] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [content] => 
Far concluded not his something extremity. Want four we face an he gate. On he of played he ladies answer little though nature. Blessing oh do pleasure as so formerly. Took four spot soon led size you. Outlived it received he material. Him yourself joy moderate off repeated laughter outweigh screened. 



                                                    [video] => /videos/5420acec0c33a1411427564.mp4
                                                )

                                        )

                                )

                            [1] => Array
                                (
                                    [topic_id] => 8
                                    [content] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [content] => 
Improve him believe opinion offered met and end cheered forbade. Friendly as stronger speedily by recurred. Son interest wandered sir addition end say. Manners beloved affixed picture men ask. Explain few led parties attacks picture company. On sure fine kept walk am in it. Resolved to in believed desirous unpacked weddings together. Nor off for enjoyed cousins herself. Little our played lively she adieus far sussex. Do theirs others merely at temper it nearer. 



                                                    [animation] => /animation/5420ad255dccc1411427621.png
                                                )

                                        )

                                )

                        )

                )

            [1] => Array
                (
                    [chapter_id] => 7
                    [version_id] => 1
                    [chapter_number] => 1
                    [Topics] => Array
                        (
                            [0] => Array
                                (
                                    [topic_id] => 9
                                    [content] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [content] => 
Full he none no side. Uncommonly surrounded considered for him are its. It we is read good soon. My to considered delightful invitation announcing of no decisively boisterous. Did add dashwoods deficient man concluded additions resources. Or landlord packages overcame distance smallest in recurred. Wrong maids or be asked no on enjoy. Household few sometimes out attending described. Lain just fact four of am meet high. 



                                                    [image] => /images/5420ac306fb831411427376.JPG
                                                )

                                        )

                                )

                            [1] => Array
                                (
                                    [topic_id] => 9
                                    [content] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [content] => 
Post no so what deal evil rent by real in. But her ready least set lived spite solid. September how men saw tolerably two behaviour arranging. She offices for highest and replied one venture pasture. Applauded no discovery in newspaper allowance am northward. Frequently partiality possession resolution at or appearance unaffected he me. Engaged its was evident pleased husband. Ye goodness felicity do disposal dwelling no. First am plate jokes to began of cause an scale. Subjects he prospect elegance followed no overcame possible it on. 



                                                    [image] => /images/5420ac48aa7201411427400.jpg
                                                )

                                        )

                                )

                        )

                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [chapter_id] => 8
                    [version_id] => 1
                    [chapter_number] => 2
                    [Topics] => Array
                        (
                            [0] => Array
                                (
                                    [topic_id] => 10
                                    [content] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [content] => 
Him boisterous invitation dispatched had connection inhabiting projection. By mutual an mr danger garret edward an. Diverted as strictly exertion addition no disposal by stanhill. This call wife do so sigh no gate felt. You and abode spite order get. Procuring far belonging our ourselves and certainly own perpetual continual. It elsewhere of sometimes or my certainty. Lain no as five or at high. Everything travelling set how law literature. 



Mr oh winding it enjoyed by b



                                                    [image] => /images/5420d951b117b1411438929.jpg
                                                )

                                        )

                                )

                            [1] => Array
                                (
                                    [topic_id] => 10
                                    [content] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [content] => 
Is education residence conveying so so. Suppose shyness say ten behaved morning had. Any unsatiable assistance compliment occasional too reasonably advantages. Unpleasing has ask acceptance partiality alteration understood two. Worth no tiled my at house added. Married he hearing am it totally removal. Remove but suffer wanted his lively length. Moonlight two applauded conveying end direction old principle but. Are expenses distance weddings perceive strongly who age domestic. 



                                                    [video] => /videos/5420d99cb852e1411439004.mp4
                                                )

                                        )

                                )

                        )

                )

            [1] => Array
                (
                    [chapter_id] => 8
                    [version_id] => 1
                    [chapter_number] => 2
                    [Topics] => Array
                        (
                            [0] => Array
                                (
                                    [topic_id] => 11
                                    [content] => Array
                                        (
                                            [0] => Array
                                                (
                                                    [content] => 
Wrote water woman of heart it total other. By in entirely securing suitable graceful at families improved. Zealously few furniture repulsive was agreeable consisted difficult. Collected breakfast estimable questions in to favourite it. Known he place worth words it as to. Spoke now noise off smart her ready. 



                                                    [image] => /images/5420d9cfa0a5f1411439055.jpg
                                                )

                                        )

                                )

                        )

                )

        )

)

是否可能,请建议。


3
不,您不能删除键,数组始终会有键。 - Kevin
没有理由想要删除数组的键。你想做什么?也许我们可以为您的问题提供一个好的解决方案。 - Xatenev
数组是键/值对的集合... 除非您只想要一个字符串,否则无法仅删除键而不删除值:$myData = implode(",\n", $myArray); - Mark Baker
删除键没有任何意义,这就是数组的目的,否则你怎么迭代它?如果你想得到的是数组(标题:=> 温暖....,片段:测试等...)那么你应该循环你的字符串,在“:”上分割它们,并创建一个新的数组,其中每个字符串的第一部分作为键,第二部分作为值。 - user4066167
你不需要从数组中删除键。只需在没有键的情况下使用它,例如:foreach ($myArray as $value){/*做任何你想做的事情,$value 是你的数组元素而没有键*/} - beerwin
我已经更新了我的问题,附带了实际的数组,我想使用foreach循环获取数据,但不是嵌套的for循环。 - user1858162
5个回答

44
尽管在PHP中,数组是“将值与键关联的类型”,有人说不可能删除键,但从某种意义上说,您可以通过替换键或用另一个数组替换数组来删除数组中的键。 我想你想要将数组更改为相当于没有显式键初始化的数组。例如,您可能有这个数组:
$arr = array(2 => 'a', 3 => 'b', 4 => 'c');

但您希望它等同于:

$arr = array('a', 'b', 'c');

可以使用函数"array_values"来完成,如下所示:

$arr = array_values($arr);

注意,数组仍然有键:0、1、2和3。

重要的是注意,整数键并不等同于数组索引。 例如,以下代码片段:

<?php
$arr = array(3 => '', 4 => '', 1 => '', 2 => '');
foreach($arr as $k => $v):
    echo "$k ";
endforeach;

将输出:

3 4 1 2

函数"array_values"可以用来确保键值和索引相同:

<?php
    $arr = array(3 => '', 4 => '', 1 => '', 2 => '');
    foreach(array_values($arr) as $k => $v):
        echo "$k ";
    endforeach;
    // outputs: 0, 1, 2, 3

我解释了如何“删除”键,但您可能希望为主题实现一个类,为主题内容(动画、图片等)创建接口,并检查SPL数据结构。


1
@PedroAmaralCouto:虽然array_values输出的索引实际上是0,1,2,3而不是1,2,3,4,但这是对问题的最佳答案。 - kachnitel
@kachnitel,你说得对。我开始说它们将从0开始,但在评论中犯了这个错误。 - Pedro Amaral Couto

0

这可行吗? 不,不可能。您无法从数组中删除键。如果您想要这样的字符串,则可以尝试使用 PHP 中的 implode 函数,如下所示。

<?php
$arr = array(
    2 => 'Title: Warmly little before cousin sussex entire set Blessing it ladyship.',
    3 => 'Snippet: Testing',
    4 => 'Category: Member',
    5 => 'Tags: little, before, entire'
);

echo implode(",\n", $arr);
?>

这将产生如下输出

标题:温暖的小表妹萨塞克斯全套祝福女士。片段:测试,类别:成员,标签:小,之前,整个

您可以查看此处implode的文档以获取更多信息。


1
如果其中一个项目包含逗号会发生什么? - beerwin

0
不,数组是一种保存键/值对的方式。如果您只想输出每行文本,请使用foreach迭代数组。

0

如果你只是想删除键,不关心之后的特定顺序(或者希望它们按函数排序),并且只需要在从0开始的数组中列出这些内容,那么你可以在数组上使用sort()

我说这种方法有点“脏”,因为它强制对事物进行排序,而不仅仅是删除数组键并重新分配它们,但这是在小型数组上完成任务的简单方法。


-2

如果您想要自己定义键,可以使用以下方法创建一个数组:

$myArray = array ("title" => "Warmly...", "snippet" => "Testing", "category" => "Member");

这将为你提供:

Array ( [title] => Warmly... [snippet] => Testing [category] => Member )

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