0

I have 10 arrays with the following format:

This is $data

Array
(
    [0] => stdClass Object
        (
                [id] => 1
                [name] => Product Name
                [category] => Product category
                [permName] => Product-Name
                [picture] => http://randomdomain.com/1.jpg
                [idUser] => 1,2,3
                [rating] => 120,880,450
                [description] => Review 1, Review 2, Review 3
                [firstName] => Name 1, Name 2, Name 3
                [lastName] => Last 1, Last 2, Last 3
                [userName] => userName 1, Username 2, Username 3
        )
    [1] => stdClass Object
        (
                [id] => 2
                [name] => Product Name 2
                [category] => Product category
                [permName] => Product-Name
                [picture] => http://randomdomain.com/1.jpg
                [idUser] => 1,2,3
                [rating] => 120,880,450
                [description] => Review 1, Review 2, Review 3
                [firstName] => Name 1, Name 2, Name 3
                [lastName] => Last 1, Last 2, Last 3
                [userName] => userName 1, Username 2, Username 3
        )  

)

I wanna turn each arrays idUser, rating, description, firstName, lastName, userName in a nested array. I was thinking of doing something like this:

foreach ($data as $row) {                   
    $firstName = $row->firstName;           
    $firstNames = explode(',', $firstName); 
}

Which turns it into array but how would I then insert it back into the original array in its original spot but as a nested array?

1 Answer 1

1
<?php
foreach( $data as $row ) {
    $firstName = $row->firstName;           
    $firstNames = explode(',', $firstName);
    $nested = array();
    foreach( $firstNames as $name ) {
       $nested[] = $name;
    }
    $row->firstName = $nested;
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Claremont, did it work ok? There might have been a mistake - I've posted a hopefully more correct version :). You can do it without a $nested variable but I'm in a rush!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.