Well, I need to be able to eliminate the repeated elements but keeping the last element, that is, eliminate the previous ones and leave the last one.
This is what I have
JavaScript
x
9
1
exists: [
2
0: {intervention_id: 2, exists: "yes"}
3
1: {intervention_id: 2, exists: "no"}
4
2: {intervention_id: 2, exists: "yes"}
5
3: {intervention_id: 5, exists: "yes"}
6
4: {intervention_id: 6, exists: "no"}
7
5: {intervention_id: 12, exists: "yes"}
8
]
9
I have to delete the previous ones.
JavaScript
1
3
1
0: {intervention_id: 2, exists: "yes"}
2
1: {intervention_id: 2, exists: "no"}
3
and leave this
JavaScript
1
2
1
2: {intervention_id: 2, exists: "yes"}
2
And this is what I need
JavaScript
1
7
1
exists: [
2
0: {intervention_id: 2, exists: "yes"}
3
1: {intervention_id: 5, exists: "yes"}
4
2: {intervention_id: 6, exists: "no"}
5
3: {intervention_id: 12, exists: "yes"}
6
]
7
I need to keep the last one and delete the previous ones
Try this but delete the last one not the previous ones.
JavaScript
1
15
15
1
function unique_multidim_array($array, $key) {
2
$temp_array = array();
3
$i = 0;
4
$key_array = array();
5
6
foreach($array as $val) {
7
if (!in_array($val[$key], $key_array)) {
8
$key_array[$i] = $val[$key];
9
$temp_array[$i] = $val;
10
}
11
$i++;
12
}
13
return $temp_array;
14
}
15
Advertisement
Answer
You could simply override the value of the current element using the same key. In this case, you will always get the last element for each ID
JavaScript
1
20
20
1
function unique_multidim_array($array, $key) {
2
$uniq = [];
3
foreach($array as $val) {
4
$curVal = $val[$key]; // shortcut of the value
5
$uniq[$curVal] = $val; // override previous value if exists
6
}
7
return array_values($uniq); // array_values to re-index array
8
}
9
10
$exists = [
11
['intervention_id' => 2, 'exists' => 'yes'],
12
['intervention_id' => 2, 'exists' => 'no'],
13
['intervention_id' => 2, 'exists' => 'yes'],
14
['intervention_id' => 5, 'exists' => 'yes'],
15
['intervention_id' => 6, 'exists' => 'no'],
16
['intervention_id' => 12, 'exists' => 'yes'],
17
];
18
$uniq = unique_multidim_array($exists, 'intervention_id');
19
print_r($uniq);
20
Output:
JavaScript
1
19
19
1
Array(
2
[0] => Array(
3
[intervention_id] => 2
4
[exists] => yes
5
)
6
[1] => Array(
7
[intervention_id] => 5
8
[exists] => yes
9
)
10
[2] => Array(
11
[intervention_id] => 6
12
[exists] => no
13
)
14
[3] => Array(
15
[intervention_id] => 12
16
[exists] => yes
17
)
18
)
19