Facebook php sdk / saving users sports / array to string conversion - php

I am trying to save the sports that a user has liked on Facebook to a database. This code is part of my Facebook login, I am using laravel.
$me contains all the user data that I receive from Facebook.
if (array_key_exists('sports', $me)){
$test = $me['sports'];
$json = strval($test); PROBLEM HERE
$data = json_decode($json, true);
$sports = array();
foreach ($data as $item) {
$sports[] = $item['name'];
}
$user->fb_sports = $sports;
}
My problem is that I am getting an array to string conversion. I am trying to convert the content of the $test variable to a string for the code that follows to work properly.
However, I don't really know what to do.
$me['sports']
returns
[{"id":"108124505876479","name":"Wakeboarding"},{"id":"112003352149145","name":"Bouldering"},{"id":"110008522357035","name":"Handball"}]
However, for my code to work properly I would need it to return this (notice the ' and ' ):
'[{"id":"108124505876479","name":"Wakeboarding"},{"id":"112003352149145","name":"Bouldering"},{"id":"110008522357035","name":"Handball"}]'
Is there any way to fix this? I simply want to save those sports to a database. Am I maybe choosing a completely wrong way here?
Any help would be much appreciated.
Thanks.
EDIT:
When I try this:
$sports = array();
foreach($me['sports'] as $sport){
// save the name i.e.
$sports[] = $sport['name'];
}
//saving array
$user->fb_sports = $sports;
I get this:

I assume you're using the PHP SDK of Facebook. This class already converts the JSON string to a PHP array. That's why "$me['sports']" is an array.
There are several options to save these sports to your database.
Do you want to save all the sports separately or all together in one string?
If you would like to save them separately you need to loop:
foreach($me['sports'] as $sport){
// save the name i.e.
your_save_function($sport['name']);
}
If you want to save all the sports together in one string I would suggest taking a look into the serialize function.
$serializedString = serialize($me['sports']);
To use the array again you need to get it from the database and unserialize it.
Another option is to convert the array to a JSON string again and save this.
$jsonString = json_encode($me['sports']);
your_save_function($jsonString);
If you want to use it as an array again you need to get it from the database and convert the JSON string to an array.
$sports = json_decode($your_db_array['sports']);
As you can see there are several ways. Maybe you can explain what you would like to do with the data as soon you saved it into the database, so I can help you choosing the best way.

Related

How to view a tinyblob object

I'm currently working with an existing database that is Mysql, and the system is built in php.
For whatever reason the builder of this system chose to store some parts of the data in blobs. One of them is a tiny blob.
In the database one of the records appears like this:
a:2:{i:0;s:3:"130";i:1;s:3:"182";}
This is viewable from the sql client I'm using. It says it's a TINYBLOB(255).
I need to be able to figure out the correct structure used to set this up so that I could build my part.
It appears to me as if I'm not seeing a "true" representation of what the data structure is.
I ran this on the php side:
public function types_get() {
$returnedTypes = $this->api->getReportTypes();
echo($returnedTypes);
$this->response($returnedTypes,REST_Controller::HTTP_OK);
}
It also produced this on the echo and response: a:2:{i:0;s:3:"130";i:1;s:3:"182";}
How would I be able to make it so I can see the true data as if it was a json string?
This data string has been created with the serialize() function. You can convert it back to a native array with the matching unserialize() function:
$string = 'a:2:{i:0;s:3:"130";i:1;s:3:"182";}';
$data = unserialize($string);
print_r($data);
Output:
Array(
[0] = 130
[1] = 182
)

string from reading file "keyname"=>"stuff","keyname2","more stuff" convert to array

I have an array stated in a codeigniter class in libraries like
$this->myArray =("keyname1"=>"fashion bags,accessories," ,"keyname2"=>"aplaku");
It works fine for what I want to do, but the array is going to get longer as my web expands and its a pain to manage like this.
So i put the array data into into sometext.txt , in the form as "keyname1"=>"stuff","keyname2"=>"stuff"
then I put it in the extra folder of codeigniter and load it using $this->load->helper('file'); and then use
$someString = read_file('extra/data.txt'); if I echo $someString I get:
"keyname1"=>"stuff","keyname2"=>"stuff"
the next thing I want to do is $this->myArray = array($someString);
It doesn't work and the issue seems to be string to array conversion
I did once use $this->anArray = func_get_args($data); but this is only for
arrays with index [0] [1]... etc
so if
$string = "keyname1","stuff","keyname2", "stuff"; //how do I do the next line
$someArray =array( $string);
Before save you can encode the array to a json and when you retreve back you can decode json.
usejson_encode($arr) for encode to json and use json_decode ($json) when retreving.

I'm fairly new to JSON, and I'm trying to get the user data from google + JSOn Code is

I'm fairly new to JSON, and I'm trying to get the user data from google +
JSOn Code is
https://www.googleapis.com/plus/v1/people?query=saurabh+sharma&key=AIzaSyADJjj8IeKuGb-woleHKTVouSlvAJUpTrs
Please help me to retrive the user profile.. in php
var_dump(json_decode(file_get_contents('https://www.googleapis.com/plus/v1/people?query=saurabh+sharma&key=AIzaSyADJjj8IeKuGb-woleHKTVouSlvAJUpTrs')));
It's indeed a bit of a mixed potato-puree (=confusion) between arrays and objects. That JSON is entirely object, except for the array 'items', which is an array of... objects.
Try this:
<?php
$strUrl = "https://www.googleapis.com/plus/v1/people?query=saurabh+sharma&key=AIzaSyADJjj8IeKuGb-woleHKTVouSlvAJUpTrs";
$strContents = file_get_contents($strUrl);
$objPeopleFeed = json_decode($strContents);
//It's an array of objects, so:
echo "<h1>{$objPeopleFeed->title}</h1>";
foreach($objPeopleFeed->items as $objUser)
{
echo "
<p>
<img src='{$objUser->image->url}' />
<a href='{$objUser->url}'>{$objUser->displayName}</a>
<i>{$objUser->objectType}</i>
</p>";
}
?>
What it does: It gets the contents from the web (which is JSON), interpretes it as JSON into valid PHP structures. From the structure, we print the title as a H1 header. From the items, which is an array, we loop through each one, print the image src from $objUser->image->url, print the user link $objUser->url with its name $objUser->displayName, and optionally its type of object $objUser->objectType that is registered on Google.
Because everything is kind of objects, you use the object to variable syntax '->xyz' instead of array indexes '["xyz"]', and I guess you got stuck there. The $objPeopleFeed->items is a non-associative array, so you use numbers to loop through the items ($objPeopleFeed->items[0] for the first item, 1 for the second, etc...). As a final cookie to you, you can use count($objPeopleFeed->items) as a results count.

zend php multiple array json_encoding

I have a problem with the json functionality in zend and js.
I try to encode a single array containing some number of models like this:
echo json_encode(Application_Model_Marker::getMarkers());
var mark = JSON.parse(jsonVal); //in js
where getMarkers is a static method that returns an array of marker models.
This works fine and when I parse it in the js script and try accessing the values of the json object it works fine.
If however I try to create and send an array of array like this:
$allData = array();
$allData['info'] = Application_Model_Marker::getMarkers();
$allData['openingHours'] = Application_Model_Openinghours::getOpeningHours();
$allData['happyHours'] = Application_Model_Happyhour::getHappyHours();
echo json_encode($allData);
It still sends all the correct information when I try to alert(jsonVal.responseText); in js.
It has three arrays each containg some arrays of objects.
However when I try to initialize a variable to the parsed json object like in the first example, I can't access the values and it seems some kind of error occurs as the program stops when I try it.
I don't quite get it as it has all the correct info when i just try to print the response text from the encoded json object.
Any ideas how to do this multidimensional json encoding?
Try this, Hopefully it'll work :
<sctript>
var mark;
eval("mark = "+jsonVal+";");
</sctrip>

How to Extract Data from a field with multiple values?

IP.Nexus puts custom fields into a table all muddled up into one row and some how pulls the correct data out.
basically my custom fields row looks like so:
a:2:{i:2;s:4:"Test";i:3;s:10:"Accounting";}
How do i select what item to pull as i would like to out put just one item not the whole row, is it with delimiters or string splitter, as i am novice with this part of mySQL
Cause i would like to echo out just the advertising on its own and also vice versa for the testing.
Thanks in advance
It's a serialized array using serialize() function so you can get its contents using unserialize($YourString);.
But I see that you string is corrupted for deserialization, because s:4: in s:4:"advertising" says that after s:4: 4 character long string is expected that advertising is not.
The data in the database is in serialized(json) form.You can turn it into simple array using unserialize.
For example;if $mystr is your string
write
$mystring=unserialize($mystring)
You will get normal array of this string
You can do
foreach($mystring as $str){
$ads[]=$str['advertising'];
}
and the resulting array $ads will be the ads you like in simple array form
Since this looks as JSon, you can use a PHP JSon module to parse each row from MySQL.
<?php
(...)
while (...) {
$obj = json_decode($row);
// do something with $obj
}

Categories