【问题标题】:Looping through an array to make another array in php循环遍历一个数组以在 php 中创建另一个数组
【发布时间】:2012-02-24 19:50:08
【问题描述】:

我有这个数组。过去几个小时我一直在尝试循环并制作另一个将问题安排在各个主题中的问题。

[23] => Array
        (
            [right] => A list of station and network addresses with corresponding gateway IP address.
            [id] => 23
            [level] => Professional
            [subject] => Array
                (
                    [0] => Array
                        (
                        [tid] => 1
                    )

                [1] => Array
                    (
                        [tid] => 6
                    )

            )

        [question] => What is an IP routing table?
        [answer] => A list of host names and corresponding IP addresses.
        [correct] => 0
    )

[22] => Array
    (
        [right] => Session hijacking attack
        [id] => 22
        [level] => Professional
        [subject] => Array
            (
                [0] => Array
                    (
                        [tid] => 1
                    )

                [1] => Array
                    (
                        [tid] => 6
                    )

            )

        [question] => How would an IP spoofing attack be best classified?
        [answer] => Session hijacking attack
        [correct] => 1
    )

[21] => Array
    (
        [right] => Repeater
        [id] => 21
        [level] => Intermediate
        [subject] => Array
            (
                [0] => Array
                    (
                        [tid] => 1
                    )

                [1] => Array
                    (
                        [tid] => 6
                    )

            )

我想做类似下面的东西。

array ( [tid1] => array (
                            [0] array (  [question] => something )
                            [1] array (  [question] => somethingelse )
                           )
         [tid2] => array (
                            [0] array (  [question] => something )
                            [1] array (  [question] => somethingelse )
                           )

但我做不到。做这个的最好方式是什么?

【问题讨论】:

  • 既然每个问题看起来都有多个主题,那么这些问题会在最终数组中出现多次(每个tid下一次)吗?
  • 是的。它会。我想按 tid 列出问题。

标签: php arrays for-loop


【解决方案1】:

假设您的数据位于名为$data 的数组中,并且由于每个问题可以有多个主题,因此每个问题可能会在最终数组中出现多次:

$final = array();
foreach($data as $datum){
    $subjects = $datum['subject'];
    foreach($subjects as $subject){
        $tid = 'tid' . $subject['tid'];
        $final[$tid][] = array('question' => $datum['question']);
    }
}

【讨论】:

    猜你喜欢
    • 2018-04-09
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 2013-11-06
    • 2023-03-23
    • 2021-11-25
    相关资源
    最近更新 更多