How to process array returned from pgsql? - php

in php i get an array from pgsql:
$res = $db
->query( "SELECT myarray FROM arrays WHERE array_name=smth" )
->fetchRow();
exit (json_encode($res));
Type in pgsql is integer[]
But in JS I get JSON with one string "{1,2,3,...,}"
How to get in 'array-way' this data?

PDO does not do any kind of type translation, everything is returned as strings. So you will have to parse the string using explode() and build a PHP array yourself.

json_encode Returns a JSON encoded string on success.
Assign the values returned by fetchrow() to a variable and try to print it before json_encode . it will be an array!!!

If you want to get the JSON decoded to an array in JavaScript, you can simply use the function eval(). But first you should make sure it is a JSON string.
See more: http://json.org/js.html

You can use something like this:
$php_array = json_decode( str_replace(
array( '[', ']', '{', '}' ),
array( '\u005B', '\u005D', '[', ']' ),
$your_pgsql_array
) );

Related

PHP json_decode return empty array

I just test this sample from php doc (http://au2.php.net/manual/en/function.json-decode.php)
here is my code:
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; echo json_decode($json, true), '<br />';?>
But it just returns an EMPTY array.
Have no idea why...Been searching around but no solution found.
PLEASE help!
You can validate at following
website: http://jsonlint.com/
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}' ;
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
$json_decoded_data = json_decode($json_string, true);
// just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key | $value <br/>";
}
you should not use echo because it is an array. use print_r or var_dump .it works fine
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
print_r(json_decode($json, true));
Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
No, it doesn't return an empty array.
Printing an array with echo just prints a string "Array()".
Use print_r or var_dump to get the structure of the variable.
In newer PHP it will also emit a notice when using echo on an array ("Array to string conversion"), so you shouldn't do it anyway. The manual you've mentioned changed to print_r.
It works fine, but you use wrong method to display array.
To display array you cannot use echo but you need to use var_dump
It works fine as others mention, but when you print the array it is converted to string, which means only the string "Array" will be printed instead of the real array data. You should use print_r(), var_dump(), var_export() or something similar to debug arrays like this.
If you turn on notices you will see:
PHP Notice: Array to string conversion in ...
The example you linked uses also var_dump for the same reason.
var_dump have pretty print in php5.4
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump( json_decode($json));

Array to String to Array conversion

I have an array that I'm storing as a string in a database to make it easier to retrieve (it's refreshed with new data every 15-30minutes via cron).
'player_list' -> 'Bob,Dave,Jane,Gordy'
'plugin_list' -> 'Plugin-A 1.4, Plugin-B 2.1, Plugin-C 0.2'
I originally store the array into the db as a string using:
$players = $liveInfo['players'] ? implode(",", $liveInfo['players']) : '';
$plugins = $liveInfo['plugins'] ? implode(",", $liveInfo['plugins']) : '';
I am currently using the following to retreive and then convert string back into array in preparation for a foreach:
$players = $server_live->player_list;
$playersArray = explode(",", $players);
$plugins = $server_live->plugin_list;
$pluginsArray = explode(",", $plugins);
For some reason, I am getting the following error: Array to string conversion I don't understand this error since I'm going from String to Array and I looked over the php.net/manual and it looks fine?...
If you need to convert from Object to String and from String to Object, then serialization is all you need to do, and you object should be supporting it.
in your case, Using Arrays, serialization is supported.
Array to String
$strFromArr = serialize($Arr);
String to Array
$Arr = unserialize($strFromArr);
for more information consider seeing the php.net website: serialize unserialize
If you must do it your way, by storing the array in the database, use the serialize() function. It's awesome!
http://php.net/manual/en/function.serialize.php
$string = serialize($array);
$array = unserialize($string);

What kind of php array is this and how do I edit it?

I am working with a project that is coded in php OOP. I have created a form that post back to itself and gets those values and puts them into a predefined array format. I say predefined because this is the way the previous coder has done it:
$plane->add(array('{"name":"Chris","age":"22"}','{"name":"Joyce","age":"45"}'));
So when I get my values from the $_POST array, I thought it would be simple, so I tried
$plane->add(array("{'name':$customerName,'age':$customerAge}"));
This is triggering an error though, it seems it's passing the actual name of the variable in as a string instead of it's value. So how do I pass those values in to that function. While we are on it, can someone explain what kind of array that is, I thought arrays were always $key=>value set, not $key:$value.
As other comments and answers have pointed out, the data is being serialized in a format known as JSON. I suggest reading up on json_encode() and json_decode()
To make your example work, you would have to do:
$data = array("name" => $customerName, "age" => $customerAge);
$plane->add(array(json_encode($data));
That looks like json:
http://sandbox.onlinephpfunctions.com/code/e1f358d408a53a8133d3d2e5876ef46876dff8c6
Code:
$array = json_decode('{"name":"Chris","age":"22"}');
print_r( $array );
And you can convert an array to json with:
$array = array("Customer" => "John");
$arrayJson = json_encode( $array);
So to put it in your context:
$array = array("Name"=>"Chris", "age" => 22);
$array2 = array("Name"=>"John", "age" => 26);
$plane->add(array( json_encode( $array),json_encode( $array2) );
It looks like it could be JSON, but might not be.
Be careful to quote everything like they have done, you didn't have any quotes around the name or age.
I've added the same sort of quotes, and used the backslashes so that PHP doesn't use them to end the string:
$plane->add(array("{\"name\":\"$customerName\",\"age\":\"$customerAge\"}"));
Be wary of user data, if $customerName and $customerAge come from POST data, you need to properly escape them using a well tested escaping function, not something you just hack together ;)
It looks like your array is an array of JSON encoded arrays. Try using:
$plane->add(array('{"name":"' . $nameVar . '","age":"' . $ageVar . '"}', ...));
If you use the following:
echo json_encode(array('name' => 'Me', 'age' => '75'), array('name' => 'You', 'age' => '30'));
You will get the following string:
[{"name":"Me","age":"75"},{"name":"You","age":"30"}]
I believe you are getting an error because what you are trying to pass to the function is not JSON while (It looks like ) the function expects an array json strings, Manually trying to write the string might not be a good idea as certain characters and type encode differently. Best to use json_encode to get you json string.
$plane->add(array(json_encode(array('name'=>$customerName,'age'=>$customerAge))));

How do I remove an Attribute from a JSON String utilizing PHP

I have a JSON result in PHP that looks like the following:
[{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ay6IAA"},"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ZfJIAU"},"Id":"a03U00000015ZfJIAU","Name":"ManagerID-00001"},
{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015axwIAA"},"Id":"a03U00000015axwIAA","Name":"ManagerID-00002"}]
I want to eliminate the Attributes (which contains Type and URL) so that the JSON result is flattened. So I'd like it to look more like:
[{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"}]
What is the best way in PHP to eliminate every instance of attributes?
//assign the orignal string to variable $json
$json = '[{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ay6IAA"},"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ZfJIAU"},"Id":"a03U00000015ZfJIAU","Name":"ManagerID-00001"},{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015axwIAA"},"Id":"a03U00000015axwIAA","Name":"ManagerID-00002"}]';
//decode the string with json_decode();
$decoded = json_decode($json);
//loop over the decoded array and populate array with Id and Name only
foreach($decoded as $d) $newarr[] = array('Id' => $d->Id, 'Name' => $d->Name);
//json encode the resulting array.
$finalJSON = json_encode($newarr);
Using json_decode(), array_map() and json_encode() should be easy enough:
function strip_arguments( $item){
$new_result = array(
'Id' => $item['Id'],
'Name' => $item['Name'],
)
return $new_result;
}
$array = json_decode( $input);
$array = array_map( 'strip_arguments', $array);
$input = json_encode( $array);
You of course may use unset() inside strip_arguments (instead of creating new array) but this will make sure any "new attribute" won't make it trough.
You can use return array(...) instead of declaring variable and chain operations to: json_encode(array_map( 'strip_arguments', json_decode( $input))); too :)
Using PHP's JSON's tools you can convert the JSON string into an array, from here use a simple foreach statement and REGEX to delete array entries.
Once this is done simply convert back into a JSON string using PHP functions and do with it as you please :-)
The functions I am thinking off are - json_decode, json_encode.
Thanks
Andrew

Unable to eval a string array

How can i change this to a JSON Array? im using the eval technique but this is not working. Im getting this kind of response from our upx server:
array(
'invoice' => array(
'id' => '4',
'realid' => '4',
'address_rev' => NULL,
'relation_data_id' => '3',
'contact_set_rev' => '3',
'business_data_rev' => '4',
'private_data_rev' => NULL,
// etc..
)
);
var_dump($newdata); // String
eval("\$newdata = \"$newdata\";");
var_dump($newdata); // Still stays as a string as shown above....
Any clue?
Ty Already!
You'll facepalm really bad when I tell you this..
But the reason it's still a string is because you wrapped it in "" inside your call to eval, and of course wrapping letters inside of quotes will make it.. (drum roll ..) a string.
eval ('$newdata = ' . $newdata . ';'); // this will do what you want
If you want to turn it into json right away, use the below:
eval ('$newdata = json_encode (' . $newdata . ');');
PHP: json_encode - Manual
var_dump($newdata); // String
eval("\$newdata = $newdata;");
var_dump($newdata); // Still stays as a string as shown above....
// eval("\$newdata = \"$newdata\";");
// ^ ^
Remove the double quotes. Your just putting it back into a string...
Although as I said above, if you want to transmit a PHP array, you should be using serialize()
You can try json_encode of php. you can try
$json_array = json_encode($your_array);
This will give you json encoded array. Then you can do json_decode on $json_array to get original contents back
Check if your php has JSON extension

Categories