来自php中JSON对象数组的重复字段/值

时间:2018-08-29 19:12:56

标签: php arrays json

我在一个网站上工作,我想在其中删除JSON对象数组中的重复字段。

我拥有的JSON对象数组是:

"rental_rates": [{
    "rate_id": 170,
    "uuid": "a3a14d20-63d1-11e8-b047-89e5d3a9513d",
    "owner_id": 38,
    "item_id": 394,
    "name": "daily",
    "term": "daily",
    "currency": "dollars",
    "rate": "56.00",
    "min_charge": "56.00",
    "created_at": "2018-05-30 06:20:43",
    "updated_at": "2018-05-30 06:21:07"
}, {
    "rate_id": 172,
    "uuid": "a3a1c500-63d1-11e8-8740-8925bbb8ada8",
    "owner_id": 38,
    "item_id": 394,
    "name": "weekly",
    "term": "weekly",
    "currency": "dollars",
    "rate": "677.00",
    "min_charge": "56.00",
    "created_at": "2018-05-30 06:21:00",
    "updated_at": "2018-05-30 06:21:07"
}],

我用来从JSON对象数组中提取字段/值的代码是:

foreach ($data['item']->rental_rates as $rental_rate)
{
echo '<span class="rental_term" style="text-align:right">'."minimum".'</span>';
echo '<span class="rental_price" style="text-align:right">$'.floatval($rental_rate->min_charge).'</span><br>';

}

上面的代码提取了以下数据,我只希望显示其中一个。

minimum $56
minimum $56


问题陈述:

我想知道我需要在foreach循环中进行哪些更改,以便它只提取一个这样的字段和值,

minimum $56

1 个答案:

答案 0 :(得分:1)

两种方式。存储已经显示的内容并进行检查:

$shown = array();
foreach ($data['item']->rental_rates as $rental_rate)
{
    if(!in_array($rental_rate->min_charge, $shown)) {
        $shown[] = $rental_rate->min_charge;
        echo '<span class="rental_term" style="text-align:right">'."minimum".'</span>';
        echo '<span class="rental_price" style="text-align:right">$'.floatval($rental_rate->min_charge).'</span><br>';
    }
}

或者创建一个由min_value索引的数组,因此将永远只有一个(仅适用于PHP> = 7.0.0以上的对象):

$rates = array_column($data['item']->rental_rates, null, 'min_charge');
foreach $rates as $rental_rate)
{
    echo '<span class="rental_term" style="text-align:right">'."minimum".'</span>';
    echo '<span class="rental_price" style="text-align:right">$'.floatval($rental_rate->min_charge).'</span><br>';
}

对于PHP <7.0.0,将true作为第二个参数并将数组解码为JSON,并在上面的代码中使用$data['item']['rental_rates']$rental_rate['min_charge']