I have the following array:
(
[https://i.imgur.com/vyGHgZN.jpg] => dummy2
[https://i.imgur.com/UYK4Agz.png] => dummy
[https://i.imgur.com/xEXdKYn.jpg] => dummy
)
Were [key]
is the image link and => dummy2
the image location on my site.
Using the following function, I remove all of the links and duplicates.
$unique=array_unique(array_values($img_array));
Which returns the following array:
(
[0] => dummy2
[1] => dummy
)
Now, I want to generate the following array:
(
[dummy]
(
[0] => https://i.imgur.com/UYK4Agz.png
[1] => https://i.imgur.com/xEXdKYn.jpg
)
[dummy2]
(
[0] => https://i.imgur.com/vyGHgZN.jpg
)
)
So I use the following function to get the links for each category:
foreach($unique as $value){
print_r(array_search($value,$img_array));
}
Which returns the following:
https://i.imgur.com/vyGHgZN.jpghttps://i.imgur.com/vyGHgZN.jpg
But as you can see, its missing a link... Looks like array_search
isn't recursive!
Tried many, many functions that are, apparently, recursive, but they all return nothing, in my case.
Any ideas?
Just loop the array and make the key value and the value the key:
$arr = array(
"https://i.imgur.com/vyGHgZN.jpg" => "dummy2",
"https://i.imgur.com/UYK4Agz.png" => "dummy",
"https://i.imgur.com/xEXdKYn.jpg" => "dummy"
);
foreach($arr as $key => $val){
$res[$val][] = $key;
}
var_dump($res);
Output:
array(2) {
["dummy2"]=>
array(1) {
[0]=>
string(31) "https://i.imgur.com/vyGHgZN.jpg"
}
["dummy"]=>
array(2) {
[0]=>
string(31) "https://i.imgur.com/UYK4Agz.png"
[1]=>
string(31) "https://i.imgur.com/xEXdKYn.jpg"
}
}
Simple foreach loop would do,
$result = [];
foreach ($arr as $key => $value) {
$result[$value][] = $key; // grouping array as per value as key
}
print_r($result);
Output:-
Array
(
[dummy2] => Array
(
[0] => https://i.imgur.com/vyGHgZN.jpg
)
[dummy] => Array
(
[0] => https://i.imgur.com/UYK4Agz.png
[1] => https://i.imgur.com/xEXdKYn.jpg
)
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.