0

I have this array from an AJAX request:

array (
    [0] => 'lat,long@id_1'
    [1] => 'lat,long@id_2'
    [2] => 'lat,long@id_3'
)

The problem here is I'm not gonna have always a 'correct-ordered' array like that, so it may look like this one:

array (
    [0] => 'lat,long@id_1'
    [1] => 'lat,long@id_2'
    [2] => 'lat,long@id_3'
    [3] => 'lat,long@id_1'
    [4] => 'lat,long@id_3'
    [5] => 'lat,long@id_2'
)

I need to get the last array value of every id_X (currently only 3 ids):

array (
    [3] => 'lat,long@id_1'
    [4] => 'lat,long@id_3'
    [5] => 'lat,long@id_2'
)

How can I find each last value of that array based on partial string (id_X)?

5
  • Do you need the indexes to be 3, 4, and 5 in the result? Commented Dec 26, 2016 at 19:02
  • 1
    Use explode() to split the string at @. Then create an associative array whose keys are id_X. You'll get just one entry for each id_X. Commented Dec 26, 2016 at 19:03
  • @barmar Nope, just the value is okay. Commented Dec 26, 2016 at 19:03
  • @barmar I will try that. Could you provide some example code? Commented Dec 26, 2016 at 19:04
  • You are totally right. I'll be back. Commented Dec 26, 2016 at 19:05

1 Answer 1

1

First do a reverse sort to ensure the latest values are parsed first. Then run them through a loop, matching the partial string to get the ID, adding the data to an array if the ID index doesn't exist yet. Last values will be added to your array, others will be neglected. Something like this:

rsort($ajaxy);

$lasts = [];

foreach($ajaxy as $str) {
    $id = substr($str, strrpos($str, '@') + 1);
    if (!isset($lasts[$id])) {
        $lasts[$id] = $str; 
    }
}

var_dump($lasts);

If you have a huge array, and you know the amount of IDs you will be getting, you can add in a check to terminate the loop when all required IDs have been added in to avoid redundant processing.

Otherwise, don't bother with the reverse sort, and simply keep overwriting previous values 'til the end, but I find this a cleaner approach. ^_^

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

3 Comments

I don't know the amount of IDs. Your code worked 100% as expected. Thank you very much!
I didn't actually bother testing, since your array wasn't in copy-pasteable format and I'm lazy past midnight hours. Jolly good it's working as expected, you're welcome. :)
Hahaha no problem, totally worked. Thanks again Markus!

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.