如何在php,mysql中的父数组中获取子数组数据

时间:2017-05-04 21:47:16

标签: php mysql arrays

下面是我的数组,但我想要父母和

中的子数据
[16363] => Array
        (
            [15] => Array
                (
                    [account_id] => 19321
                    [aum] => 104853.92
                    [cl_user_id] => 16363
                    [text] => MICHAEL ANDRISANO INDIVIDUAL
                    [fname] => MICHAEL
                    [lname] => ANDRISANO
                    [account_number] => 906566540
                )

            [16] => Array
                (
                    [account_id] => 19322
                    [aum] => 196539.78
                    [cl_user_id] => 16363
                    [text] => MICHAEL ANDRISANO INDIVIDUAL
                    [fname] => MICHAEL
                    [lname] => ANDRISANO
                    [account_number] => 906566600
                )

        )

我想要输出如下

 [16363] => Array
        (
            [text] => MICHAEL ANDRISANO
            [cl_id] => 16363
            [nodes] => Array
                (
                    [0] => Array
                        (
                     [account_id] => 19321
                    [aum] => 104853.92
                    [cl_user_id] => 16363
                    [text] => MICHAEL ANDRISANO INDIVIDUAL
                    [fname] => MICHAEL
                    [lname] => ANDRISANO
                    [account_number] => 906566540
                        )

                    [1] => Array
                        (
                            [cl_id] => 16363
                            [account_id] => 19322
                            [aum] => 196539.78
                            [text] => MICHAEL ANDRISANO INDIVIDUAL (906566600)
                            [account_number] => 906566600

                        )
                )

        )

1 个答案:

答案 0 :(得分:0)

我不知道您的任何变量名称,但是假设您的原始数组名为$parent,并且您希望将其解析为$clients

只需遍历$parent中的每条记录,然后循环遍历子数组,并将它们全部放在一个新数组中。以下是如何执行此操作的示例。您问题中的预期输出对于不同的[node]元素具有不同数量的键,因此我不确定您想要实现的目标,但希望这会让您开始。

<?php
//This is what will be our final array (your expected output)
$clients = array();

foreach ($parent as $key=>$children)
{
    // Build the initial $clients meta data.
    $clients[$key] = array (
        // It seems the following data is identical, so we'll just grab from the first child
        'text' => $children[key($children)]['fname'] . ' ' . $children[key($children)]['lname'],
        'cl_id' => $children[key($children)]['cl_user_id'],
        'nodes' => array()
    );

    // Now populate the nodes
    foreach ($children AS $child)
    {
        $clients[$key]['nodes'][] = array (
            'account_id' => $child['account_id'],
            'cl_id' => $child['cl_id'],
            'aum' => $child['aum'],
            'text' => $child['text'],
            'account_number' => $child['account_number']
        );
    }
}
?>