【问题标题】:Looping through an array and turn strings into nested array循环遍历数组并将字符串转换为嵌套数组
【发布时间】:2012-02-23 15:46:26
【问题描述】:

我有 10 个数组,格式如下:

这是$数据

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); 
}

这会将它变成数组,但是我如何将它插入到原始数组中的原始位置,但作为嵌套数组?

【问题讨论】:

    标签: php


    【解决方案1】:
    <?php
    foreach( $data as $row ) {
        $firstName = $row->firstName;           
        $firstNames = explode(',', $firstName);
        $nested = array();
        foreach( $firstNames as $name ) {
           $nested[] = $name;
        }
        $row->firstName = $nested;
    }
    ?>
    

    【讨论】:

    • 嗨克莱蒙特,它工作正常吗?可能有一个错误 - 我已经发布了一个希望更正确的版本:)。你可以在没有 $nested 变量的情况下做到这一点,但我很着急!
    猜你喜欢
    • 1970-01-01
    • 2017-10-22
    • 2018-05-20
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    相关资源
    最近更新 更多