John Davidson

php - Is there a way to remove all repeated keys except the last one in array?

0 comments
Message:


I have array of messages received from server, with key seen_by which contain users saw the message, it's structure :


[1] => Array
(
[seen_by] => Array
(
[1] => user_1
[2] => user_2
[3] => user_3
)

)

[2] => Array
(
[seen_by] => Array
(
[2] => user_2
[3] => user_3
)

)
[3] => Array
(
[seen_by] => Array
(
[3] => user_3
)

)

where they keys in seen_by array is user_id,


what i want to do is since user_2 already in the seen_by array of the second message ,so remove it from the first seen_by array , and since user_3 in seen_by array of third message , remove from the first two messages


I want to get array like


[1] => Array
(
[seen_by] => Array
(
[1] => user_1
)

)

[2] => Array
(
[seen_by] => Array
(
[2] => user_2
)

)
[3] => Array
(
[seen_by] => Array
(
[3] => user_3
)

)


My Answer:
Yes, you can achieve this by using a combination of array functions in PHP. Here's an example code snippet to remove all repeated keys except the last one in an array:

php
// Your array of messages
$messages = [
['seen_by' => ['user1', 'user2']],
['seen_by' => ['user1', 'user3']],
['seen_by' => ['user2', 'user3']],
['seen_by' => ['user1', 'user2', 'user3']],
];

// Loop through the messages array
foreach ($messages as $key => $message) {
// Get the unique values of the 'seen_by' key in reverse order
$uniqueSeenBy = array_unique(array_reverse($message['seen_by']));

// Update the 'seen_by' key in the message array
$messages[$key]['seen_by'] = array_reverse($uniqueSeenBy);
}

// Output the updated messages array
print_r($messages);


This code snippet will remove all repeated keys except the last one in the 'seen_by' key of each message in the array.

Rate this post

3 of 5 based on 6619 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us