0

I am working on a website in which I want to remove duplicate fields from JSON object array.

The JSON object array which I have is:

"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"
}],

The code which I am using in order to pull fields/values form JSON object array is:

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>';

}

The above code is pulling the following data and I want only one to be shown.

minimum $56
minimum $56


Problem Statement:

I am wondering what changes I need to make in the foreach loop so it pull only one field and value like this,

minimum $56

1 Answer 1

1

Two ways. Store what has already been displayed and check for it:

$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>';
    }
}

Or create an array indexed by the min_value so there will only ever be one (only works on objects as of 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>';
}

For PHP < 7.0.0, decode the JSON as an array passing true as the second argument and use $data['item']['rental_rates'] and $rental_rate['min_charge'] in the code above instead.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.