在PHP中格式化数组作为示例中给出的必需输出[关闭]

i have an php array as:

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
        )
)

I want to format given array into json something like below, I want them to be categorized by the product_name field given in the array. I did tried but i was nowhere near to that result. I tried my code is below:

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);

But i want as below:

{
    "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"
            }
        ],
    }
    ]
} 

The important thing here is that, you just need to use the $report->product_name as your key and make it a multi dimentional again on setting the new array, and then finally, just encode it. Example:

$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;

Sample Output

Use json_encode

It's pretty self-explanatory

Edit: Before encoding to JSON you can consolidate your array. You'll need to use your desired value as key.

Code example:

$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 ;
}

json_encode will convert any given value (except a resource) into a JSON value:

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

would return:

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

In your case you are looking to convert an array of Objects of type StdClass

You might want to consider making your class implement JsonSerializable (php 5.4 upwards) and create a method jsonSerialize which would output each of your objects in the desired array format.

example :

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

more info : http://php.net/manual/en/jsonserializable.jsonserialize.php