循环遍历数组并将字符串转换为嵌套数组

时间:2012-02-23 07:27:32

标签: php

我有10个阵列,格式如下:

这是$ 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
        )  

)

我想在嵌套数组中将每个数组idUser,rating,description,firstName,lastName,userName。我在考虑做这样的事情:

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

将其转换为数组,但是如何将其插入原始数据中的原始数据中,但作为嵌套数组?

1 个答案:

答案 0 :(得分:1)

<?php
foreach( $data as $row ) {
    $firstName = $row->firstName;           
    $firstNames = explode(',', $firstName);
    $nested = array();
    foreach( $firstNames as $name ) {
       $nested[] = $name;
    }
    $row->firstName = $nested;
}
?>