在PHP中获得所需的输出

时间:2017-01-14 11:28:01

标签: php arrays sorting format

我有以下格式的数据

$data = 
 Array
(
[0] => Array
    (
        [cdt] => 2016-01-01
        [name] => Harish
        [hour] => 8.5
    )

[1] => Array
    (
        [cdt] => 2016-01-01
        [name] => Preeti
        [hour] => 8
    )

[2] => Array
    (
        [cdt] => 2016-01-01
        [name] => Sunit
        [hour] => 9
    )

[3] => Array
    (
        [cdt] => 2016-01-01
        [name] => Prabhakar
        [hour] => 8
    )

[4] => Array
    (
        [cdt] => 2016-01-02
        [name] => Prabhakar
        [hour] => 2
    )

[5] => Array
    (
        [cdt] => 2016-01-04
        [name] => Preeti
        [hour] => 8
    )

[6] => Array
    (
        [cdt] => 2016-01-04
        [name] => Sunit
        [hour] => 9
    )

[7] => Array
    (
        [cdt] => 2016-01-04
        [name] => Harish
        [hour] => 9.5
    )

[8] => Array
    (
        [cdt] => 2016-01-04
        [name] => Prabhakar
        [hour] => 10
    )

[9] => Array
    (
        [cdt] => 2016-01-05
        [name] => Preeti
        [hour] => 10
    )

[10] => Array
    (
        [cdt] => 2016-01-05
        [name] => Sunit
        [hour] => 8
    )

[11] => Array
    (
        [cdt] => 2016-01-05
        [name] => Harish
        [hour] => 9
    )

[12] => Array
    (
        [cdt] => 2016-01-05
        [name] => Prabhakar
        [hour] => 9
    )
)

我希望它采用这种格式

Array
(
  [0] => 2016-01-01, Harish: 8.5, Preeti: 8, Sunit: 9, Prabhakar: 8
  [1] => 2016-01-02, Prabhakar: 2
  [2] => 2016-01-04, Preeti: 8, Sunit: 9, Harish: 9.5, Prabhakar: 10
  [3] => 2016-01-05, Preeti: 10, Sunit: 8, Harish: 9, Prabhakar: 9
)

我尝试了一些循环,但那些没有帮助。我在foreach循环中并不擅长,但我怀疑它会解决这个问题。

以下是我尝试过的代码

$k=0;
for($i = 0; $i < sizeOf($uniqueDates); $i++)
{
    $chartData[$i] = 'y: '.$data[$i]['cdt'].', ';
    for($j = $k; $j < Sizeof($data); $j++)
    {
        if($uniqueDates[$i] == $data[$j]['cdt'])
        {
            $chartData[$i] .= $data[$j]['name'].': '.$data[$j]['hour'].', ';
        }

    }
    $k++;

}

在$ uniqueDates中,我获取了所有唯一日期,$ data是包含上述格式数据的数组。

1 个答案:

答案 0 :(得分:0)

这看起来非常简单。您所要做的就是整理您的条目,然后根据您想要的输出格式化它们。

看看这个简单的例子:

Array
(
    [0] => 2016-01-01, Harish: 10, Preeti: 8, Sunit: 9, Prabhakar: 8
    [1] => 2016-01-02, Prabhakar: 2
    [2] => 2016-01-04, Preeti: 8, Sunit: 9, Harish: 9.5, Prabhakar: 10
    [3] => 2016-01-05, Preeti: 10, Sunit: 8, Harish: 9, Prabhakar: 9
)

上述代码的输出显然是:

{{1}}