0

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?

0

2 Answers 2

1

Simple foreach loop would do,

$result = [];
foreach ($arr as $key => $value) {
    $result[$value][] = $key; // grouping array as per value as key
}
print_r($result);

Demo

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
        )

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

1 Comment

@keanu_reeves Welcome! If my solution solved your problem, please accept the answer.
1

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"
  }
}

https://3v4l.org/0E9Vm

1 Comment

Yes? We posted at the same time. Except I made an effort in helping OP understand what the code does.

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.