0

There's JSON data with Offers

foreach($json['offers'] as $offer) 

Every offer has data that contains country

"countries":[{"name":"United States","code":"US"}]

How do I remove all the offers if they dont include for example "US"?

As far as I understand I should use array_map right? But how do I tell it to remove those that doesn't include value instead of those who does include value I define?

3
  • 2
    array_map() is for changing (all) data. You want array_filter(). Commented Nov 28, 2018 at 8:51
  • as @Dormilich you should use array_filter - var_dump(array_filter($offers, function($offer) { return ('US' === $offer['countries'][0]['code'] ?? null); })); Commented Nov 28, 2018 at 8:59
  • Possible duplicate of array_filter with assoc array? Commented Nov 28, 2018 at 11:53

3 Answers 3

1

You need to use array_filter()

$json['offers'] = array_filter($json['offers'], function($item){
    return $item['countries'][0]['code'] == "US";
});

Check result in demo

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

Comments

0

If I don't misunderstood your question, then simple array_filter() will do the trick for you.

<?php

$json = '[{"countries":[{"name":"United States","code":"US"}]},{"countries":[{"name":"United Kingdom","code":"UK"}]},{"countries":[{"name":"Canada","code":"CA"}]}]';
$decode = json_decode($json,1);
$new = array_filter($decode, function ($var) {
    return ($var['countries'][0]['code'] != 'US');
});
print_r($new);
?>

DEMO: https://3v4l.org/LtPEl

Comments

0

Thank you guys for answers, but I've did it in another way..

$salys2 = array("US");      
$salys = array_map('trim', $salys2);    


if (!in_array($offer['countries'][0]['code'], $salys)) {

    // skipping
    continue;
}

Could someone explain me why are we keeping [0] between countries and code?

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.