从 JSON 数组中提取一个对象/组并使用 PHP 将其保存到一个新文件中。我挂断了代码的数组部分

我有以下 json 结构,我试图循环并从中提取产品:


[]JSON

->{0}

-->[]username

-->[]avatar

-->[]rep

-->[]products

-->[]groups

-->[]feedbacks

-->[]online

-->[]staff

我试图仅将产品对象作为 JSON 文件保存。这是我需要的唯一结果并删除/取消设置其余部分:


[]JSON

->{0}

-->[]products

但我似乎有点困惑,因为我不熟悉数组如何围绕 PHP 工作。这是我目前正在尝试的一个角度:


<?php

$str = file_get_contents('test.json');

$json_decoded = json_decode($str,true);

foreach($json_decoded as $index){

unset($json_decoded[$index][???]);

        }

file_put_contents('cleaned.json', json_encode($json_decoded));

?> 

我加了???我迷路的地方,这就是我所得到的。我一直超级困惑。我知道结构将始终与上述相同,因此从技术上讲,我可以单独删除用户名、头像、代表、组、反馈、在线和员工。这很好。


下面是一个json结构的例子:


[{"username":["1"],"avatar":["yellow"],"rep":["etc"],"products":["Big"],"groups":["small"],"feedbacks":["small"],"online":["small"],"staff":["small"]}]

在此先感谢您,即使是朝着正确的方向推动也是非常感谢的。


Qyouu
浏览 224回答 3
3回答

慕的地8271018

您可以像这样组成一个新产品数组:$products = [];foreach($json_data as $value) {&nbsp; &nbsp; $products[]['products'] = $value['products'];}file_put_contents('cleaned.json', json_encode($products));这将产生像这样的 json 对象:[&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "products": ["Big-01"]&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "products": ["Big-02"]&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "products": ["Big-03"]&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "products": ["Big-04"]&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "products": ["Big-05"]&nbsp; &nbsp; }]

月关宝盒

从你的片段。尝试这个。<?php$str = '[{"username":["1"],"avatar":["yellow"],"rep":["etc"],"products":["Big"],"groups":["small"],"feedbacks":["small"],"online":["small"],"staff":["small"]}]';$json_decoded = json_decode($str,true);foreach($json_decoded as $value) {&nbsp; &nbsp; $products = $value['products'];}print_r( $products);?>&nbsp;输出Array(&nbsp; &nbsp; [0] => Big)

胡说叔叔

创建一个新数组 ( $products),遍历旧数组,并将其设置products为一个属性,而不是设置unset每个数组。$products = [];foreach ($json_decoded as $index) {&nbsp; $products[$index] = [&nbsp; &nbsp; 'products' => $json_decoded[$index]['products']&nbsp; ];}file_put_contents('cleaned.json', json_encode($products));
打开App,查看更多内容
随时随地看视频慕课网APP