使用$ result = json_decode(json_encode($ result),true)将std对象数组传递给数组数组

$result = AssetModel::biGetRecords($userId);

The result is array of objects.

like this

array(100) {
[0]=>
object(stdClass)#1120 (3) {
["id"]=>
int(1058064)
["asset_id"]=>
string(16) "12345"
["name"]=>
string(22) "David"
}
[1]=>
object(stdClass)#1116 (3) {
["id"]=>
int(1058088)
["asset_id"]=>
string(16) "34567"
["name"]=>
string(6) "Smith"

so I use

$result = json_decode(json_encode($result), true); 

to transfer array of std objects to array of arrays.

It works fine. But then when new records added in. Suddenly

 $result = json_decode(json_encode($result), true); 

instead of return array of array, it returns empty array now.

My guess is that some new records with some invalid characters that make json_encode returns invalid json string so the next step json_decode would not work?

echo "get results: ";

echo count($result);

$result = json_decode(json_encode($result), true);

echo " count data results again: ";

echo count($result);

the result is

get results: 397320 count data results again: 0

So my questions are

  • $result = json_decode(json_encode($result), true) is not error proof way to transfer array of objects to array of array?
  • if above case is true, what is the easiest way to transfer array of objects to array of arrays?

Thanks!

After your comment about limiting the results, my thought is you're hitting a memory limit on your script. I'd try performing the encode/decode on a per item basis...

This will perform the translation at a per item level.

$mocklist = array_fill( 0, 100, (object) array('foo'=>'foo','bar'=>'bar') );

array_walk( $mocklist, function( &$value ){
  $value = json_decode( json_encode( $value ), true );
});

print_r( $mocklist );

You could also leverage this to locate which $value becomes empty in a crude manual debugging way.

array_walk( $mocklist, function( $value ){
  if( empty( json_decode( json_encode( $value ), true ) )
  {
    print_r( $value );
    exit('Found the empty one!');
  }
});

Suggested by Scuzzy, I should use php.net/manual/en/function.json-last-error-msg.php to report the error.

Yes. there is an error when I do the json_encode.

Malformed UTF-8 characters, possibly incorrectly encoded

I used to run to this UTF-8 malformed issue frequently before, due to two reasons

  • Database tables were not utf8 encoded.
  • data transfer was in xml format instead of json format

But since the database' tables are mostly encoded as utf8 today, and more and more the data transfer in json format rather than xml, I had not run into utf8 characters issue for a long time.

Now go back to my issue, my tables are

ENGINE=InnoDB DEFAULT CHARSET=utf8 

I need to figure out why the query results from these tables still gave me utf8 Malformed problems.

Thanks!