Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 20007

How to convert this PHP array of objects to json?

I have an array of 10 objects that I am trying to convert to JSON. The array is being stored in a variable called $invoices. Below is the ouput of var_dump($invoices) shorted to only the first object.

I've tried the following:

$invoices = json_encode($invoices, FALSE);
$invoices = json_encode($invoices, TRUE);
$invoices = json_encode($invoices, JSON_UNESCAPED_UNICODE);

However, the output is always:

string(31) "[{},{},{},{},{},{},{},{},{},{}]"

How can this array be properly converted to JSON?

Note: I am running PHP 5.5.9

Update:

It turns out the problem is due the fact that json_encode won't work with "protected member variables." Is there a way to declare those variables as public if I don't have access to the class that created them?

array(10) {
  [0]=>
  object(QuickBooks_IPP_Object_Invoice)#285 (1) {
    ["_data":protected]=>
    array(22) {
      ["Id"]=>
      array(1) {
        [0]=>
        string(6) "{-224}"
      }
      ["SyncToken"]=>
      array(1) {
        [0]=>
        string(1) "0"
      }
      ["MetaData"]=>
      array(1) {
        [0]=>
        object(QuickBooks_IPP_Object_MetaData)#282 (1) {
          ["_data":protected]=>
          array(2) {
            ["CreateTime"]=>
            array(1) {
              [0]=>
              string(25) "2014-12-07T09:48:47-08:00"
            }
            ["LastUpdatedTime"]=>
            array(1) {
              [0]=>
              string(25) "2014-12-07T09:48:47-08:00"
            }
          }
        }
      }
      ["CustomField"]=>
      array(1) {
        [0]=>
        object(QuickBooks_IPP_Object_CustomField)#292 (1) {
          ["_data":protected]=>
          array(3) {
            ["DefinitionId"]=>
            array(1) {
              [0]=>
              string(4) "{-1}"
            }
            ["Name"]=>
            array(1) {
              [0]=>
              string(6) "Crew #"
            }
            ["Type"]=>
            array(1) {
              [0]=>
              string(10) "StringType"
            }
          }
        }
      }
      ["DocNumber"]=>
      array(1) {
        [0]=>
        string(4) "1038"
      }
      ["TxnDate"]=>
      array(1) {
        [0]=>
        string(10) "2014-12-07"
      }
      ["Line"]=>
      array(2) {
        [0]=>
        object(QuickBooks_IPP_Object_Line)#263 (1) {
          ["_data":protected]=>
          array(5) {
            ["Id"]=>
            array(1) {
              [0]=>
              string(4) "{-1}"
            }
            ["LineNum"]=>
            array(1) {
              [0]=>
              string(1) "1"
            }
            ["Amount"]=>
            array(1) {
              [0]=>
              string(9) "155555.00"
            }
            ["DetailType"]=>
            array(1) {
              [0]=>
              string(19) "SalesItemLineDetail"
            }
            ["SalesItemLineDetail"]=>
            array(1) {
              [0]=>
              object(QuickBooks_IPP_Object_SalesItemLineDetail)#765 (1) {
                ["_data":protected]=>
                array(2) {
                  ["ItemRef"]=>
                  array(1) {
                    [0]=>
                    string(4) "{-3}"
                  }
                  ["TaxCodeRef"]=>
                  array(1) {
                    [0]=>
                    string(6) "{-NON}"
                  }
                }
              }
            }
          }
        }
        [1]=>
        object(QuickBooks_IPP_Object_Line)#748 (1) {
          ["_data":protected]=>
          array(3) {
            ["Amount"]=>
            array(1) {
              [0]=>
              string(9) "155555.00"
            }
            ["DetailType"]=>
            array(1) {
              [0]=>
              string(18) "SubTotalLineDetail"
            }
            ["SubTotalLineDetail"]=>
            array(1) {
              [0]=>
              string(0) ""
            }
          }
        }
      }
      ["TxnTaxDetail"]=>
      array(1) {
        [0]=>
        object(QuickBooks_IPP_Object_TxnTaxDetail)#287 (1) {
          ["_data":protected]=>
          array(1) {
            ["TotalTax"]=>
            array(1) {
              [0]=>
              string(1) "0"
            }
          }
        }
      }
      ["CustomerRef"]=>
      array(1) {
        [0]=>
        string(5) "{-11}"
      }
      ["BillAddr"]=>
      array(1) {
        [0]=>
        object(QuickBooks_IPP_Object_BillAddr)#284 (1) {
          ["_data":protected]=>
          array(7) {
            ["Id"]=>
            array(1) {
              [0]=>
              string(5) "{-11}"
            }
            ["Line1"]=>
            array(1) {
              [0]=>
              string(13) "1045 Main St."
            }
            ["City"]=>
            array(1) {
              [0]=>
              string(13) "Half Moon Bay"
            }
            ["CountrySubDivisionCode"]=>
            array(1) {
              [0]=>
              string(2) "CA"
            }
            ["PostalCode"]=>
            array(1) {
              [0]=>
              string(5) "94213"
            }
            ["Lat"]=>
            array(1) {
              [0]=>
              string(10) "37.4559621"
            }
            ["Long"]=>
            array(1) {
              [0]=>
              string(11) "-122.429939"
            }
          }
        }
      }
      ["ShipAddr"]=>
      array(1) {
        [0]=>
        object(QuickBooks_IPP_Object_ShipAddr)#814 (1) {
          ["_data":protected]=>
          array(7) {
            ["Id"]=>
            array(1) {
              [0]=>
              string(5) "{-11}"
            }
            ["Line1"]=>
            array(1) {
              [0]=>
              string(13) "1045 Main St."
            }
            ["City"]=>
            array(1) {
              [0]=>
              string(13) "Half Moon Bay"
            }
            ["CountrySubDivisionCode"]=>
            array(1) {
              [0]=>
              string(2) "CA"
            }
            ["PostalCode"]=>
            array(1) {
              [0]=>
              string(5) "94213"
            }
            ["Lat"]=>
            array(1) {
              [0]=>
              string(10) "37.4559621"
            }
            ["Long"]=>
            array(1) {
              [0]=>
              string(11) "-122.429939"
            }
          }
        }
      }
      ["DueDate"]=>
      array(1) {
        [0]=>
        string(10) "2015-01-06"
      }
      ["TotalAmt"]=>
      array(1) {
        [0]=>
        string(9) "155555.00"
      }
      ["ApplyTaxAfterDiscount"]=>
      array(1) {
        [0]=>
        string(5) "false"
      }
      ["PrintStatus"]=>
      array(1) {
        [0]=>
        string(11) "NeedToPrint"
      }
      ["EmailStatus"]=>
      array(1) {
        [0]=>
        string(6) "NotSet"
      }
      ["Balance"]=>
      array(1) {
        [0]=>
        string(9) "155555.00"
      }
      ["Deposit"]=>
      array(1) {
        [0]=>
        string(1) "0"
      }
      ["AllowIPNPayment"]=>
      array(1) {
        [0]=>
        string(5) "false"
      }
      ["AllowOnlinePayment"]=>
      array(1) {
        [0]=>
        string(5) "false"
      }
      ["AllowOnlineCreditCardPayment"]=>
      array(1) {
        [0]=>
        string(5) "false"
      }
      ["AllowOnlineACHPayment"]=>
      array(1) {
        [0]=>
        string(5) "false"
      }
    }
  }
  [1]=>
  object(QuickBooks_IPP_Object_Invoice)#830 (1) {
    ["_data":protected]=>
    array(22) {
    ...
    ...

Upvotes: 3

Views: 11448

Answers (4)

Saurabh Koshatwar
Saurabh Koshatwar

Reputation: 46

The best way is to implement JsonSerializable class and define the jsonSerialize() function

Example:

class MyObj implements JsonSerializable{
    protected $id;
    protected $name;

    function getId() { return $this->$id; }
    function getName() { return $this->$name; }
  
     public function jsonSerialize() {
                return [
                'Id' => $this->getId(),
                'Name' => $this->getName()
            ];
        }
}

// $arrofobj is array of objects of type MyObj 
json_encode($arrofobj);  //this will convert array of objects to JSON

Upvotes: 2

Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 20007

In the end, this is the solution I chose to use:

function objectToArray ($object) {
    if(!is_object($object) && !is_array($object))
        return $object;

    return array_map('objectToArray', (array) $object);
}

From here: How do I convert an object to an array?

With a multidimensional array (and not an array of objects containing protected variables), json_encode() works great.

Upvotes: 0

Rangad
Rangad

Reputation: 2160

If these classes cannot implement JsonSerializable you may access the protected properties using Reflection.

Example:

class Publisher {
    protected $name;
    protected $id;
    public function __construct($id, $name) {
        $this->id = $id;
        $this->name = $name;
    }
}

function getPublisherExportData($publishers) {
    $out = [];
    foreach($publishers as $publisher) {
        $currentPData = [];
        $refl = new ReflectionClass($publisher);
        $props = $refl->getProperties(ReflectionProperty::IS_PROTECTED);
        foreach($props as $prop) {
            $prop->setAccessible(true);
            $currentPData[$prop->getName()] = $prop->getValue($publisher);
        }
        $out[] = $currentPData;
    }

    return $out;
}

var_dump(json_encode(getPublisherExportData([new Publisher(12, 'My Name'), new Publisher(15, 'NameProperty')]), JSON_PRETTY_PRINT));

Will result in:

string(121) "[ { "name": "My Name", "id": 12 }, { "name": "NameProperty", "id": 15 } ]"

However, you will need to handle object graphs and conditional exports yourself. Depending on the required json output you might think about replacing $out with an instance of stdClass and write using the $out->{$prop->getName()} = $val syntax to it.

If you are able to use your custom implementations you could add a method using get_object_vars($this) to avoid most of the code above, however if you could do that you should consider implementing JsonSerializable which is meant for that task.

Upvotes: 1

Lynn
Lynn

Reputation: 121

you need write a function for your class "QuickBooks_IPP_Object_MetaData' and get a array. you may would see this question, Serializing PHP object to JSON

Upvotes: 0

Related Questions