1

I've been trying for a while. I have tried several things to fix this, but I just can't get it to work.

My code:

<?php
if (is_array($row))
{
    foreach ($row as $data) {

        echo array_unique($data->username);
    } 
}
?>

It gives me the following error

Message: array_unique() expects parameter 1 to be array, string given

I have no idea what is going on with this. I have even tried placing the array_unique in the $row.

So like:

<?php
if (is_array($row))
{
    foreach (array_unique($row) as $data) {

        echo $data->username;
    } 
}
?>

But this gives me another error:

Object of class stdClass could not be converted to string

I have no idea what's going on. I have searched for hours but haven't found anything on here. Any help is greatly appreciated. Thanks.

3
  • output of: print_r($row); is ... ? expected output is ... ? Commented Mar 28, 2015 at 2:22
  • 1
    array_unique works on flat arrays, even if you cast (array) $row as array it still won't work, just create a temporary container to check Commented Mar 28, 2015 at 2:22
  • 1
    Hey @Ghost You have like answered 75% of all my questions! :) Thanks for that :) What exactly do you mean? Thanks :) Commented Mar 28, 2015 at 2:23

1 Answer 1

1

You can't use array_unique on multi-dimensional arrays when you're looking inside the depth. Its works on flat one, and certainly won't work on strings. An alternative is to create another container for that and use usernames as keys, then you'll get unique ones.

Since you haven't shown the array/object structure, here a little bit on an idea on the comment I gave above:

$container = array();
foreach($row as $data) {
    if(!isset($container[$data->username])) {
        $container[$data->username] = $data;
    }
}
// $container = array_values($container); // optional simple reindex
Sign up to request clarification or add additional context in comments.

1 Comment

@TaylorSwift sure glad i was able to help again

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.