我有以下数组:
(
[https://i.imgur.com/vyGHgZN.jpg] => dummy2
[https://i.imgur.com/UYK4Agz.png] => dummy
[https://i.imgur.com/xEXdKYn.jpg] => dummy
)
[key]
是图片链接,=> dummy2
是我网站上的图片位置。
使用以下功能,我删除了所有链接和重复项。
$unique=array_unique(array_values($img_array));
哪个返回以下数组:
(
[0] => dummy2
[1] => dummy
)
现在,我想生成以下数组:
(
[dummy]
(
[0] => https://i.imgur.com/UYK4Agz.png
[1] => https://i.imgur.com/xEXdKYn.jpg
)
[dummy2]
(
[0] => https://i.imgur.com/vyGHgZN.jpg
)
)
因此,我使用以下函数来获取每个类别的链接:
foreach($unique as $value){
print_r(array_search($value,$img_array));
}
哪个返回以下内容:
https://i.imgur.com/vyGHgZN.jpghttps://i.imgur.com/vyGHgZN.jpg
但是您可以看到,它缺少一个链接... array_search
似乎不是递归的!
尝试了许多许多函数,这些函数显然是递归的,但就我而言,它们都不返回任何值。
有什么想法吗?
答案 0 :(得分:2)
只需循环数组,然后将键值和值设为键:
$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);
输出:
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"
}
}
答案 1 :(得分:1)
简单的foreach循环就可以了,
$result = [];
foreach ($arr as $key => $value) {
$result[$value][] = $key; // grouping array as per value as key
}
print_r($result);
输出:-
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
)
)