如何访问 PHP 中的 JSON 元素,如数组对象?

Posted

技术标签:

【中文标题】如何访问 PHP 中的 JSON 元素,如数组对象?【英文标题】:How can I access JSON elements in PHP like array object? 【发布时间】:2018-05-30 14:01:21 【问题描述】:

通过触发this Webhook,我收到一个order object,当我在电子邮件中输出它时,它看起来像这样:

数组"id":1154,"parent_id":0,"status":"pending","currency":"EUR","version":"3.2.3","prices_include_tax":true," date_created":"日期":"2017-12-15 15:58:42.000000","timezone_type":1,"timezone":"+00:00","date_modified":"date":"2017-12-15 15:58:42.000000","timezone_type":1,"timezone":"+00:00","discount_total":"0","discount_tax":"0","shipping_total":"0"," shipping_tax":"0","cart_tax":"0","total":"6.50","total_tax":"0","customer_id":0,"order_key":"wc_order_5a33f1321ba43","billing": "first_name":"Peter","last_name":"Parker","company":"","address_1":"Baker Str.","address_2":"2","city":"London","state":"","postcode":"50668","country":"DE","email":"something@ gmail.com","phone":"01627423","shipping":"first_name":"Peter","last_name":"Parker","company":"","address_1":"Baker Str.","address_2":"2","city":"London","state":"","postcode":"50668","country":"DE","payment_method":"cod ","payment_method_title":"贝 Abholung","交易 _id":"","customer_ip_address":"...","customer_user_agent":"mozilla/5.0 (macintosh; intel mac os x 10_13_2) applewebkit/537.36 (khtml, like 壁虎)铬/blabla safari/537.36","created_via":"checkout","customer_note":"","date_completed":null,"date_paid":null,"cart_hash":"be97db19eba58864b9166961ce22a706","number":"1154","meta_data ":["id":4731,"key":"_billing_title","value":"1","id":4732,"key":"_shipping_title","value":"1" ],"line_items":"18":,"tax_lines":[],"shipping_lines":"19":,"fee_lines":[],"coupon_lines":[]

能否请您指出一种访问此 JSON 元素的可能性,以便我可以从 $order 对象的某些部分构建消息?我尝试将$data = json_decode($order)$data->date_created 结合使用,但是当我丢弃最后一部分时,这并没有给我任何帮助。

【问题讨论】:

【参考方案1】:

它是 json,除了开头的 Array 部分(假设那是您尝试访问 date_created):

您可以像以前一样使用json_decode(),但date_created 也是一个数组,因此您还需要从中选择您想要的项目。

$data = json_decode($order, true);

echo $data['date_created']['date']; // 2017-12-15 15:58:42.000000

因此,如果您想要客户名称,例如:

echo $data['billing']['first_name'].' '.$data['billing']['last_name'];

通过print_r($data)'ing,您可以看到它的结构。

Array
(
    [id] => 1154
    [parent_id] => 0
    [status] => pending
    [currency] => EUR
    [version] => 3.2.3
    [prices_include_tax] => 1
    [date_created] => Array
        (
            [date] => 2017-12-15 15:58:42.000000
            [timezone_type] => 1
            [timezone] => +00:00
        )

    [date_modified] => Array
        (
            [date] => 2017-12-15 15:58:42.000000
            [timezone_type] => 1
            [timezone] => +00:00
        )

    [discount_total] => 0
    [discount_tax] => 0
    [shipping_total] => 0
    [shipping_tax] => 0
    [cart_tax] => 0
    [total] => 6.50
    [total_tax] => 0
    [customer_id] => 0
    [order_key] => wc_order_5a33f1321ba43
    [billing] => Array
        (
            [first_name] => Peter
            [last_name] => Parker
            [company] => 
            [address_1] => Baker Str.
            [address_2] => 2
            [city] => London
            [state] => 
            [postcode] => 50668
            [country] => DE
            [email] => something@gmail.com
            [phone] => 01627423
        )

    [shipping] => Array
        (
            [first_name] => Peter
            [last_name] => Parker
            [company] => 
            [address_1] => Baker Str.
            [address_2] => 2
            [city] => London
            [state] => 
            [postcode] => 50668
            [country] => DE
        )

    [payment_method] => cod
    [payment_method_title] => Bei Abholung
    [transaction _id] => 
    [customer_ip_address] => ...
    [customer_user_agent] => mozilla/5.0 (macintosh; intel mac os x 10_13_2) applewebkit/537.36 (khtml, like gecko) chrome/blabla safari/537.36
    [created_via] => checkout
    [customer_note] => 
    [date_completed] => 
    [date_paid] => 
    [cart_hash] => be97db19eba58864b9166961ce22a706
    [number] => 1154
    [meta_data] => Array
        (
            [0] => Array
                (
                    [id] => 4731
                    [key] => _billing_title
                    [value] => 1
                )

            [1] => Array
                (
                    [id] => 4732
                    [key] => _shipping_title
                    [value] => 1
                )

        )

    [line_items] => Array
        (
            [18] => Array
                (
                )

        )

    [tax_lines] => Array
        (
        )

    [shipping_lines] => Array
        (
            [19] => Array
                (
                )

        )

    [fee_lines] => Array
        (
        )

    [coupon_lines] => Array
        (
        )

)

如果您想要简单 输出,您可以使用递归函数遍历数组,该函数将生成您的电子邮件。

echo '<h2>Order Details</h2>'.php_EOL;
echo order_details(json_decode($json, true));

function order_details($items, $str = null)    
    foreach ($items as $key => $item) 
        if (is_array($item)) 
            $str .= PHP_EOL.'<h3>'.ucwords(str_replace('_', ' ', $key)).'</h3>'.PHP_EOL;
            $str .= order_details($item, $str);
         else 
            $str .= '<b>'.ucwords(str_replace('_', ' ', $key)).'</b>: '.$item.'</br>'.PHP_EOL;
        
    
    return $str;

输出如下:https://3v4l.org/l9BS4

<h2>Order Details</h2>
<b>Id</b>: 1154</br>
<b>Parent Id</b>: 0</br>
<b>Status</b>: pending</br>
<b>Currency</b>: EUR</br>
<b>Version</b>: 3.2.3</br>
<b>Prices Include Tax</b>: 1</br>

<h3>Date Created</h3>
<b>Date</b>: 2017-12-15 15:58:42.000000</br>
<b>Timezone Type</b>: 1</br>
<b>Timezone</b>: +00:00</br>

<h3>Date Modified</h3>
<b>Date</b>: 2017-12-15 15:58:42.000000</br>
<b>Timezone Type</b>: 1</br>
<b>Timezone</b>: +00:00</br>
<b>Discount Total</b>: 0</br>
<b>Discount Tax</b>: 0</br>
<b>Shipping Total</b>: 0</br>
<b>Shipping Tax</b>: 0</br>
<b>Cart Tax</b>: 0</br>
<b>Total</b>: 6.50</br>
<b>Total Tax</b>: 0</br>
<b>Customer Id</b>: 0</br>
<b>Order Key</b>: wc_order_5a33f1321ba43</br>

<h3>Billing</h3>
<b>First Name</b>: Peter</br>
<b>Last Name</b>: Parker</br>
<b>Company</b>: </br>
<b>Address 1</b>: Baker Str.</br>
<b>Address 2</b>: 2</br>
<b>City</b>: London</br>
<b>State</b>: </br>
<b>Postcode</b>: 50668</br>
<b>Country</b>: DE</br>
<b>Email</b>: something@gmail.com</br>
<b>Phone</b>: 01627423</br>

<h3>Shipping</h3>
<b>First Name</b>: Peter</br>
<b>Last Name</b>: Parker</br>
<b>Company</b>: </br>
<b>Address 1</b>: Baker Str.</br>
<b>Address 2</b>: 2</br>
<b>City</b>: London</br>
<b>State</b>: </br>
<b>Postcode</b>: 50668</br>
<b>Country</b>: DE</br>
<b>Payment Method</b>: cod</br>
<b>Payment Method Title</b>: Bei Abholung</br>
<b>Transaction  Id</b>: </br>
<b>Customer Ip Address</b>: ...</br>
<b>Customer User Agent</b>: mozilla/5.0 (macintosh; intel mac os x 10_13_2) applewebkit/537.36 (khtml, like gecko) chrome/blabla safari/537.36</br>
<b>Created Via</b>: checkout</br>
<b>Customer Note</b>: </br>
<b>Date Completed</b>: </br>
<b>Date Paid</b>: </br>
<b>Cart Hash</b>: be97db19eba58864b9166961ce22a706</br>
<b>Number</b>: 1154</br>

<h3>Meta Data</h3>

<h3>0</h3>
<b>Id</b>: 4731</br>
<b>Key</b>: _billing_title</br>
<b>Value</b>: 1</br>

<h3>1</h3>
<b>Id</b>: 4732</br>
<b>Key</b>: _shipping_title</br>
<b>Value</b>: 1</br>

<h3>Line Items</h3>

<h3>18</h3>

<h3>Tax Lines</h3>

<h3>Shipping Lines</h3>

<h3>19</h3>

<h3>Fee Lines</h3>

<h3>Coupon Lines</h3>

【讨论】:

谢谢! Array 是输出的一部分,而不是我尝试的一部分。我只是将$order 添加为电子邮件的消息正文。我认为这是我无法正确访问 JSON 的部分问题!? 你应该检查它是否在$order的字符串中,如果是你应该找到它被添加的地方并修复它,因为它不应该在那里,如果它不是json_decode($order, true)应该返回一个数组,如果是,它将返回null。如果您由于某种原因无法删除它,您可以随时通过检查它是否存在以及是否将其剥离来解决 - 3v4l.org/Hule3【参考方案2】:

当你使用时

$data = json_decode($order);

它会创建一个对象,将这个对象转换成一个关联数组你只需要传递一个参数

$data = json_decode($order, true);

【讨论】:

以上是关于如何访问 PHP 中的 JSON 元素,如数组对象?的主要内容,如果未能解决你的问题,请参考以下文章

像数组一样访问json对象中的元素[重复]

访问从 iPhone 应用程序发送的 PHP 中的数组对象

如何访问 JSON 对象数组的第一个元素?

PHP 如何轻松访问PHP中的JSON(如具有多个字段的JSON记录集)

如何访问json中的数组元素?

如何在PHP中解析json