根据示例中给出的输出,用PHP格式化数组


Formatting the Array in PHP as required output given in the example

我有一个php数组,如下所示:

Array
(
    [0] => stdClass Object
        (
            [price_with_discount] => 2025.00
            [sales_date] => 2014-09-02
            [sales_type] => 1
            [part_id] => 6
            [part_number] => SN14FW-KU027OR03
            [part_rate] => 2025.00
            [sales_status] => 2
            [product_name] => Ladies Fashion Wear 
            [model_number] => Bamboo Shawl Natural
        )
    [1] => stdClass Object
        (
            [price_with_discount] => 1700.00
            [sales_date] => 2014-09-02
            [sales_type] => 1
            [part_id] => 23
            [part_number] => SN14FW-KU015PL01
            [part_rate] => 1700.00
            [sales_status] => 2
            [product_name] => Ladies Fashion Wear 
            [model_number] => Allo Cotton Shawl
        )
    [2] => stdClass Object
        (
            [price_with_discount] => 1850.00
            [sales_date] => 2014-09-02
            [sales_type] => 1
            [part_id] => 31
            [part_number] => SN14FW-KU022GR06
            [part_rate] => 1850.00
            [sales_status] => 2
            [product_name] => Ladies Fashion Wear 
            [model_number] => Bamboo Stole 
        )
    [3] => stdClass Object
        (
            [price_with_discount] => 1840.00
            [sales_date] => 2014-09-03
            [sales_type] => 1
            [part_id] => 49
            [part_number] => SN13FW-KU113BR02
            [part_rate] => 1840.00
            [sales_status] => 2
            [product_name] => Accessories
            [model_number] => Bangle
        )
)

我想将给定的数组格式化为json,如下所示,我希望它们按照数组中给定的product_name字段进行分类。我确实试过了,但离那个结果还差得很远。我试过我的代码如下:

foreach ($reports as $report) {
            $product_name = str_replace(' ', '_', trim($report->product_name));
                $r[$product_name][] = array(
                        'part_number' => $report->part_number,
                        'part_rate' => $report->part_rate,
                    ); 
        }
        $reports = json_encode($r,JSON_PRETTY_PRINT);

但我想要如下:

{
    "Data":[
    {
        "ProductName":"Ladies_Fashion_Wear",
        "ProuuctItems": [
            {
                "part_number": "SN14FW-KU027OR03",
                "part_rate": "2025.00"
            },
            {
                "part_number": "SN14FW-KU015PL01",
                "part_rate": "1700.00"
            },
        ]
    },
    {
        "ProductName":"Accessories",
        "ProuuctItems": [
            {
                "part_number": "SN14FW-KU030GR02",
                "part_rate": "2040.00"
            }
        ],
    }
    ]
} 

这里重要的是,您只需要使用$report->product_name作为密钥,在设置新数组时使其再次成为多维数组,然后最后对其进行编码。示例:

$r['Data'] = array();
foreach($reports as $report) {
    if(!isset($r['Data'][$report->product_name])) {
        // initial insertion
        $r['Data'][$report->product_name] = array(
            'ProductName' => $report->product_name,
            'ProductItems' => array(),
        );
    }
    // push it inside once created
    $r['Data'][$report->product_name]['ProductItems'][] = array(
        'part_number' => $report->part_number, 
        'part_rate' => $report->part_rate
    );
}
// simple reindex
$r['Data'] = array_values($r['Data']);
echo '<pre>';
$final = json_encode($r, JSON_PRETTY_PRINT);
echo $final;

样本输出

json_encode将任何给定值(资源除外)转换为json值:

json_encode(array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5));

将返回:

{"a":1,"b":2,"c":3,"d":4,"e":5}

在您的情况下,您希望转换StdClass 类型的对象数组

您可能需要考虑让类实现JsonSerializable(php 5.4以上)并创建一个方法jsonSerialize,该方法将以所需的数组格式输出每个对象。

示例:

public function jsonSerialize() {
        return array('ProductName'=>'myName','productItems'=>array('part_number'=>'123456'))
    }

更多信息:http://php.net/manual/en/jsonserializable.jsonserialize.php

使用json_encode

这是一个非常不言自明的

编辑:在编码为JSON之前,您可以合并您的数组。您需要使用您想要的值作为关键字。

代码示例:

$result = array();
foreach($source as $item) {
    $product_name= key($item);
    $other_attributes = current($item); // repeat for all other attributes
    if(!isset($result[$product_name])) {
        $result[$product_name] = array();
    }
    $result[$product_name][] = $other_attributes ;
}