0

I am pulling out a list of popular product IDs into an array that looks like this

Array
(
    [0] => stdClass Object
        (
            [popular_product] => 2,60
        )

    [1] => stdClass Object
        (
            [popular_product] => 12,61,60
        )

    [2] => stdClass Object
        (
            [popular_product] => 2
        )

    [3] => stdClass Object
        (
            [popular_product] => 9
        )

    [4] => stdClass Object
        (
            [popular_product] => 14
        )

)

I want to create a new array that shows me what the most popular products are by count, my approach is this

Combine all popular_product ids into one long comma seperated string like this

2,60,12,61,60,2,9,14

Is this the most efficient approach?

1
  • 2
    Comma seperated strings isn't really a good practice, why don't you just split the id's up? So you get something like ['object'] -> [key] -> [productId] Commented Mar 28, 2018 at 9:29

1 Answer 1

2

Since php7 you can pass array of objects to array_column, so it will be something like:

print_r(implode(',', array_column($a, 'popular_product')));

For php5 you need to use a foreach or some array_ methods, for example:

print_r(implode(',', array_reduce($a, function($t,$v) { $t[] = $v->popular_product; return $t; }, [])));
Sign up to request clarification or add additional context in comments.

Comments

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.