PHP中的高级数组重建

时间:2016-06-17 13:54:05

标签: php arrays multidimensional-array slice linechart

我根据标签关联预测用户兴趣。这些关联将使用ChartJS绘制在多线图中。我已经到了数据格式几乎可以在客户端使用的地步。

不要被阵列的大小吓到。我的问题很简单,但很难解决,所以看来。

考虑以下数组(包括示例数据):

array:3 [▼
  "timespan" => "day",
  "labels" => array:3 [▼ // Date labels based on timespan
    0 => "2016-06-10"
    1 => "2016-06-11"
    2 => "2016-06-12"
  ],
  "data" => array:2 [▼
    0 => array:3 [▼
      "id" => 16473,
      "name" => "FooTag"
      "timeline" => array:3 [▼
        0 => array:3 [▼
          "Date" => "2016-06-10"
          "Frequency" => 2
          "Score" => 4.0
        ]
        1 => array:3 [▼
          "Date" => "2016-06-12"
          "Frequency" => 2
          "Score" => 4.0
        ]
      ]
    ]
    1 => array:3 [▼
      "id" => 10814,
      "name" => "BarTag"
      "timeline" => array:1 [▼
        0 => array:3 [▼
          "Date" => "2016-06-10"
          "Frequency" => 2
          "Score" => 3.0
        ],
        1 => array:3 [▼
          "Date" => "2016-06-11"
          "Frequency" => 10
          "Score" => 20.0
        ]
      ]
    ]
  ]
]

...确保data[i][timeline]内的每个时间轴都涵盖每个日期标签(2016-06-10,206-06-11,2016-06-12)。如果该特定日期标签的时间轴中没有可用数据,则必须插入空数组。

结果将是:

array:3 [▼
  "labels" => array:3 [▼ // Date labels based on timespan
    0 => "2016-06-10"
    1 => "2016-06-11"
    2 => "2016-06-12"
  ]
  "timespan" => "day"
  "data" => array:2 [▼
    0 => array:3 [▼
      "id" => 16473,
      "name" => "FooTag"
      "timeline" => array:3 [▼
        0 => array:3 [▼
          "Date" => "2016-06-10"
          "Frequency" => 2
          "Score" => 4.0
        ],
        1 => array:0 [], // No data for label 2016-06-11, empty array added
        2 => array:3 [▼
          "Date" => "2016-06-12"
          "Frequency" => 2
          "Score" => 4.0
        ]
      ]
    ]
    1 => array:3 [▼
      "id" => 10814,
      "name" => "BarTag"
      "timeline" => array:1 [▼
        0 => array:3 [▼
          "Date" => "2016-06-10"
          "Frequency" => 2
          "Score" => 3.0
        ],
        1 => array:3 [▼
          "Date" => "2016-06-11"
          "Frequency" => 10
          "Score" => 20.0
        ],
        2 => array:0 [], // No data for label 2016-06-12, empty array added
      ]
    ]
  ]
]

在这种情况下,每个关联的标签都包含每个日期的数据。否则,在绘制图表时,数据(频率和分数)将与正确的日期不匹配。

我希望这样做。提前谢谢!

1 个答案:

答案 0 :(得分:1)

假设$array['labels']是明确的日期列表,$array['data'][$i]['timeline']将始终按升序排序,并且永远不会包含不在$array['labels']中的日期:

$labels = $array['labels'];

foreach ($array['data'] as &$tag) {
   foreach ($labels as $i => $date) {
      if (!isset($tag['timeline'][$i]) || $tag['timeline'][$i]['Date'] != $date) {
         $blank = [];
         array_splice($tag['timeline'], $i, 0, [$blank]);
      }
   }
}