I am trying to fetch some data from an API and put it into an array and then to MySQL.
My Code:
$find_sql = "SELECT * FROM `scrape`";
$users_to_scrape = $app['db']->fetchAll($find_sql);
$instagram = $app['instagram'];
$oauth = json_decode(file_get_contents($app['oauth_path']));
$instagram->setAccessToken($oauth);
foreach($users_to_scrape as $user_to_scrape) {
printf("Getting info for %s <%s>\n", $user_to_scrape['instagram_id'], $user_to_scrape['user_name']);
$follows = $instagram->getUser($user_to_scrape['instagram_id'], 999);
foreach($follows->data as $follow) {
echo var_dump($follows);
$data = array(
'instagram_id' => $follow->id,
'followed_by_instgram_id' => $user_to_scrape['instagram_id'],
'user_name' => $follow->username,
'full_name' => iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($follow->full_name)),
'profile_picture' => $follow->profile_picture,
'followers' => $follow->counts->followed_by,
'follows' => $follow->counts->follows
);
printf("+ %s <%s>\n", $data['instagram_id'], $data['user_name']);
//skapa tabell med follows (instagram_id,
if ($follow->counts->followed_by >= "30000") {
$app['db']->insert('follows', $data);
}
}
}
The Vardump returns this:
object(stdClass)#111 (2) {
["meta"]=>
object(stdClass)#112 (1) {
["code"]=>
int(200)
}
["data"]=>
object(stdClass)#113 (7) {
["username"]=>
string(9) "Dimbos"
["bio"]=>
string(97) "•Have fun in life Contact: info#skogen.com"
["website"]=>
string(24) "http://www.life.com"
["profile_picture"]=>
string(106) "https://xxertt.com/hphotos-ak-xaf1/t51.2885-19/11311351_362556250614181_543_a.jpg"
["full_name"]=>
string(10) "Dimbo"
["counts"]=>
object(stdClass)#114 (3) {
["media"]=>
int(113)
["followed_by"]=>
int(256673)
["follows"]=>
int(345)
}
["id"]=>
string(8) "38353560"
}
}
And the error I receive is this:
Notice: Trying to get property of non-object in /var/www/script.php on line 40
On line 40 we have this:
'instagram_id' => $follow->id,
I also get error on the following set arrays.
Can't really figure it out.
Because $follows->data is a stdClass object, iterating it with foreach will loop over each of its properties individually, returning the value of each property. This means that though id is present in the loop, it is merely the last data element of the loop, inaccessible by its property name.
Using the foreach, the iterator value of $follow results directly in the values rather than properties, as in:
// Value of $follow on each loop iteration:
"Dimbos"
"•Have fun in life Contact: info#skogen.com"
"http://www.life.com"
// etc...
You don't need the foreach loop. Instead, access each element of $follows->data directly:
// Remove the foreach loop
$data = array(
// Each property is directly accessible in $follows->data
'instagram_id' => $follows->data->id,
'followed_by_instgram_id' => $user_to_scrape['instagram_id'],
'user_name' => $follows->data->username,
'full_name' => iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($follows->data->full_name)),
'profile_picture' => $follows->data->profile_picture,
'followers' => $follows->data->counts->followed_by,
'follows' => $follows->data->counts->follows
);
printf("+ %s <%s>\n", $data['instagram_id'], $data['user_name']);
//skapa tabell med follows (instagram_id,
if ($follows->data->counts->followed_by >= "30000") {
$app['db']->insert('follows', $data);
}
You could create a variable that references the data property, allowing you to access those inner properties with less code, but I don't see it as necessary.
// Refer to data in $follow
$follow = $follows->data;
echo $follow->id;
echo $follow->counts->followed_by;
// etc...
Related
I'm new to Laravel, and I want to store this array in DB.
This is the php code of my array:
$socialNetwork = array();
$socialNetwork[0]["name"]= "Facebook";
$socialNetwork[0]["account"]= "facebook_account";
$socialNetwork[1]["name"]= "Twitter";
$socialNetwork[1]["account"]= "twitter_account";
$socialNetwork[2]["name"]= "Instagram";
$socialNetwork[2]["account"]= "insta_account";
The var_dump() looks like this:
array(3) {
[0] => array(2) {
["name"] => string(8) "Facebook"
["account"] => string(16) "facebook_account"
}
[1] => array(2) {
["name"] => string(7) "Twitter"
["account"] => string(15) "twitter_account"
}
[2] => array(2) {
["name"] => string(9) "Instagram"
["account"] => string(13) "insta_account"
}
}
I've tried several things but I can't get it to work!
Please help with the code. The table name is socialAccounts
Add a column in your database for this field; a JSON or TEXT type will do the job.
Next, you should add the column to the $casts array on your SocialAccount model:
protected $casts = [
'facebook_account' => 'array',
];
Now, whenever you retrieve this value, it will be deserialized for you.
To store the value, just use json_encode():
$social_account->facebook_account = json_encode($facebookArrayData);
$social_account->save();
You can read more on attribute casting in the docs; https://laravel.com/docs/7.x/eloquent-mutators#attribute-casting
i want to edit a script i found online. is has an hardcoded array like this.
$servers = array(
'Google Web Search' => array(
'ip' => '',
'port' => 80,
'info' => 'Hosted by The Cloud',
'purpose' => 'Web Search'
),
'Example Down Host' => array(
'ip' => 'example.com',
'port' => 8091,
'info' => 'ShittyWebHost3',
'purpose' => 'No purpose'
)
);
Result:
array(2) {
["Google Web Search"]=>
array(4) {
["ip"]=>
string(0) ""
["port"]=>
int(80)
["info"]=>
string(19) "Hosted by The Cloud"
["purpose"]=>
string(10) "Web Search"
}
["Example Down Host"]=>
array(4) {
["ip"]=>
string(11) "example.com"
["port"]=>
int(8091)
["info"]=>
string(14) "ShittyWebHost3"
["purpose"]=>
string(10) "No purpose"
}
}
I put this data in a database and want to make the same array but i dont seem to get it working
This is the code i added to make an array:
$query ="SELECT name, ip, port, hosting FROM sites";
$select = $conn->prepare($query);
$select->execute(array());
$testing = array();
while($rs = $select->fetch(PDO::FETCH_ASSOC)) {
$testing[] = array($rs['name'] => array('ip'=> $rs['ip'], 'port'=> $rs['port'], 'hosting'=> $rs['hosting']));
}
The result from this is:
array(2) {
[0]=>
array(1) {
["Google Web Search"]=>
array(3) {
["ip"]=>
string(10) "google.com"
["port"]=>
string(2) "80"
["hosting"]=>
string(19) "Hosted by The Cloud"
}
}
[1]=>
array(1) {
["Example Down Host"]=>
array(3) {
["ip"]=>
string(11) "example.com"
["port"]=>
string(2) "09"
["hosting"]=>
string(14) "ShittyWebHost3"
}
}
}
is there a way to make the bottom array the same as the top array, i dont want to edit the whole script, this seems easier.
You are appending a new integer indexed element with [] and then adding 2 nested arrays. Instead, add the name as the key:
$testing[$rs['name']] = array('ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']);
Since you specify the columns in the query and they are the same as the array keys, then just this:
$testing[$rs['name']] = $rs;
When you assign a value to an array you use the syntax $arr[key] = $value. If you omit the key during the assignment, $value will be assigned to the next available integer key of the array, starting from 0.
This is an example of how it works:
$arr = array();
$arr[] = 'one';//Empty, so insert at 0 [0=>'one']
$arr[] = 'two';//Last element at 0, so use 1 [0=>'one',1=>'two']
$arr[6]= 'three';//Key is used, so use key [0=>'one',1=>'two',6=>'three']
$arr[] = 'four';//Max used integer key is 6, so use 7
print_r($arr);//[0=>'one',1=>'two',6=>'three',7=>'four']
So, when in your code you are using
$testing[] = array(
$rs['name'] => array(
'ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']
)
);
You are assigning the newly created array to the positions 0,1,2,..N.
To avoid this, just specify the key explicitly, using the value you really want, like
$testing['name'] => array(
'ip'=> $rs['ip'],
'port'=> $rs['port'],
'hosting'=> $rs['hosting']
);
You can read more about arrays in the documentation
Side note
If you don't mind having an extra column in the generated arrays, you can rewrite entirely your code this way:
$query ="SELECT name, ip, port, hosting FROM sites";
$results = $conn->query($query)->fetchAll(PDO::FETCH_ASSOC);
$testing = array_column($results,null,'name');
It's slightly slower, but very handy in my opinion, PDOStatement::fetchAll retrieves all the data at once and array_column using null as second parameter does reindex the array with the wanted column as key.
PDOStatement::fetchAll
array_column
I have a database and a table user. when i perform below code i got output as below.
$searchQuery = array('userID' => '2');
$collection = $db->mydatabase->users;
$cursor = $collection->find()->limit(2);
foreach ($cursor as $doc) {
var_dump($doc);
}
Output:
array(4) {
'_id' =>
class MongoId#8 (1) {
public $$id =>
string(24) "56c8216d7f8b9a0e148b4567"
}
'userID' =>
int(7)
'lastTimeOnline' =>
string(19) "2016-02-20 01:48:53"
'displayName' =>
string(0) ""
}
array(4) {
'_id' =>
class MongoId#9 (1) {
public $$id =>
string(24) "56c8216d7f8b9a0e148b4568"
}
'userID' =>
int(2)
'lastTimeOnline' =>
string(19) "2016-02-20 01:48:53"
'displayName' =>
string(0) ""
}
Now i need to find only those records whose userID is 2, so i change the code as below.
$searchQuery = array('userID' => '2');
$collection = $db->mydatabase->users;
$cursor = $collection->find($searchQuery)->limit(2);
foreach ($cursor as $doc) {
var_dump($doc);
}
but now the output is blank :-(
I have two doubts.
A) why 2nd code to fetch userId=2 is not working
B)why on both cases var_dump($cursor) is giving below output and why not detail of $doc
class MongoCursor#5 (0) {
}
Seems like the userID in database is saved as Integer and your are trying to query using a string parameter, try to change the query array to the following:
$searchQuery = array('userID' => 2);
You are storing the userId as an integer and in the query you are using a string due to which you are find nothing so instead of writing 2 like this '2' write it like this 2
Something I noticed which patches the problem:
If I return $this->_data instead of $this->_data[0] - and then use $object->data()[0], it does work as expected... However, I would like to return the [0] in the function.
Before you start saying that this is a duplicate - this question is unlike most other questions regarding this error.
I'm getting the following error when trying to access $this->_data[0] in my class:
Cannot use object of type stdClass as array
This is the function/line the error is being triggered on:
public function data(){
return $this->_data[0]; //<- line 75
}
To my understanding, this error occurs when I try to use an object as I would use an array. However, when I var_dump($this->_data), I get the following result:
array(1) {
[0]=> object(stdClass)#34 (10) {
["uid"]=> string(1) "0"
["nid"]=> string(3) "374"
["id"]=> string(8) "YicnaxYw"
["txt_content"]=> NULL
["path"]=> string(32) "/uploads/images/png/YicnaxYw.png"
["image"]=> string(1) "1"
["timestamp"]=> string(10) "1448192959"
["file_ext"]=> string(3) "png"
["file_type"]=> string(9) "image/png"
["originalFilename"]=> string(23) "2015-11-22_12-49-17.png"
}
}
Where clearly this variable is of type array(1) with a [0] element ..
Could someone tell me what I'm doing wrong?
Thanks in advance.
#Xeli $this->_data[0]->nid causes the same error
Fatal error: Cannot use object of type stdClass as array in /home3/ramzes/includes/classes/UploadItem.php on line 75
UploadItem.php:75
public function data(){
return $this->_data[0]->nid;
}
$this->_data[0] is a fetchAll(PDO::FETCH_OBJ) object with the results from the query
EDIT:
I've set up a test for this at http://ideone.com/66I3wO - I'm storing your object in an array and I can access $this->_data[0]->nid just fine.
<?php
class Test
{
public $_data = [];
public function __construct() {
$this->_data[0] = (object) [
'uid' => '0',
'nid' => '374',
'id' => 'YicnaxYw',
'txt_content' => null,
'path' => '/uploads/images/png/YicnaxYw.png',
'image' => '1',
'timestamp' => '1448192959',
'file_ext' => 'png',
'file_type' => 'image/png',
'originalFilename' => '2015-11-22_12-49-17.png'
];
}
public function data(){
return $this->_data[0];
}
}
$test = new Test();
echo $test->_data[0]->nid;
var_dump( $test->data() );
I think the PDO returns an object which is implemented via something like this: http://php.net/manual/en/class.iteratoraggregate.php
When you var_dump it, it will look like an array, but it's not.
You could change your data function to this:
function data() {
foreach($this->_data as $data) {
return $data;
}
}
If you explicitly convert to array then you can access the index like you want to:
$return = (array) $this->_data;
return $return[0];
I have an array of database objects and I'm using foreach() to present the names and projects. Good, now the customer doesn't want duplicate names for when one person has multiple projects. This has to do with variable scope and this is my failed attempt to pull this stunt off. Here's a partial var_dump of the array of objects.
array [
0 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "Bone density scanner analysis"
}
1 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "analysis of foot"
}
]
What I want to end up with is:
array [
0 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "Bone density scanner analysis"
}
1 => {
["lastName"]=>
string(1) ""
["projectName"]=>
string(16) "analysis of foot"
}
]
Here's what I was thinking that doesn't seem to work:
function suppress_name($name){
global $string;
return ($name == $string) ? '' : $string;
}
function overall() {
//$result = database call to get objects
foreach ($result as $item) {
$string = $item->lastName;
$rows = array('Name' => suppress_name($item->lastName), 'project' => $item->projectName);
}
}
Researching I see several references to array_unique() which I use for a flattened array, but I can't see that it would help me here. OK, I thought I could make a function, like the above, to handle duplicates and use the $global but think I'm not grasping how to use globals in this instance. I'm happy to be pointed to a better way, or better search terms. Does this make sense?
Here is a possible approach to your solution, where we store the last names in a one dimensional array then check against it through each iteration of the array. If the lastName is in the array then set the value to ''.
Note the use of the reference (&).
<?php
$arrays = array(
array('lastName' => 'w', 'projectName' => 'Bone density scanner analysis'),
array('lastName' => 'w', 'projectName' => 'analysis of foot')
);
$last_names = array();
foreach($arrays as &$array){
if( in_array($array['lastName'],$last_names) ){
$array['lastName'] = '';
}else{
$last_names[] = $array['lastName'];
}
}
echo '<pre>',print_r($arrays),'</pre>';
It would be easier to work with nested arrays
array [
0 => {
["lastName"]=> string(1) "w"
["projects"]=> array [
0 => {
["projectName"] => string(29) "Bone density scanner analysis"
}
1 => {
["projectName"]=> string(16) "analysis of foot"
}
1 => {
["lastName"] => string(1) "x"
["projects"] => array [
0 => {
["projectName"] => string(16) "analysis of head"
} ]
}
]