Twitter API JSON Help - php

I've been trying to play with the Twitter API a bit and this is what I have so far:
function get_twitter_user_data($user_id, $limit = 3)
{
$twitter_username = 'twitter';
$twitter_json = #file_get_contents('http://api.twitter.com/1/statuses/user_timeline.json?&include_rts=1&screen_name='.$twitter_username.'&count='.$limit);
$twitter_data = json_decode($twitter_json);
if ( ! $twitter_data) {
return array();
}
foreach ($twitter_data[0]->user as $user) {
$image = $user->profile_image_url;
}
// doesn't do anything
echo $image.'<br/><br/>';
// works
echo $twitter_data[0]->user->profile_image_url;
}
Been trying to figure this out far too long. And yes, I've done research but the solutions that I've found have no worked for me. I think maybe I'm just extremely tired and can't see the issue right now.
Anybody mind explaining why looping through $twitter_data doesn't work but output a direct value with $twitter_data[0]->user->profile_image_url does?
Many thanks.

You have to do this instead:
foreach ($twitter_data as $status) {
$user = $status->user;
foreach ($twitter_data[0]->user as $user) iterates over the values of the poster of the first status.

Related

MongoDB MapReduce (1.2) PHP with parameter

I'm trying to 'parameterize' a MongoDB MapReduce on PHP and seem to be hitting a wall. I feel like I'm missing something obvious since I'm not super experienced in PHP or javascript. I can get the map reduce to work and return what I need if I hard code the value I want it to check.
For example
$client = new MongoDB\Client;
$collection = $client->selectCollection('collection','responses');
$map = new MongoDB\BSON\Javascript('function() { if(this.response == "Yes") { emit("matches", 1)}};');
$reduce = new MongoDB\BSON\Javascript('function(key, values) { return Array.sum(values)};');
$out = ['inline' => 1];
$data = $collection->mapReduce($map, $reduce, $out);
foreach ($data as $d) {
var_dump($d);
}
I would like this if(this.response == "Yes") "Yes" value to be a variable so I can filter on other responses.
I've tried a handful of ways and I can't get it to work.
Any tips or ideas?
Thanks!

Undefined Offset 0: Laravel

I HAVE already read through the other similar questions on stackoverflow and none of them have helped me to find a solution.
This has be completely confused, what was once working has randomly broken and I have no idea whats wrong, the error doesn't seem logical to me i'll show you what i mean.
public function nGetOverviewAccounts()
{
$results = Account::where('archive', '=', false)->select('id', 'display_name', 'server_ip_address', 'server_password', 'status_type_id', 'account_type_id')->get()->toArray();
$index = 0;
$accounts = [];
foreach($results as $result)
{
$accountType = AccountType::where('id', $result['account_type_id'])->select('name')->get()->toArray();
$statusType = StatusType::where('id', $result['status_type_id'])->select('name')->get()->toArray();
return $accountType[0]['name']; //this works
$accounts[$index]['account_type'] = $accountType[0]['name']; //this doesnt..
$accounts[$index]['status_type'] = $statusType[0]['name'];
$index++;
}
return $accounts;
}
That code is right next to each other in the function. The array $accountType looks like this.
0:{name: "Google"}
Which shows that it has an index of 0 but its not working.
EDIT: PLEASE READ
Im going to clear something up i seems to have put it across wrongly to you guys, the return statement is added by me AFTER i get the undefined index error i only added it to the code to show that it works when i return it but when i try to assign its value to another variable (without the return statement) i get the undefined index error.
Try this:
public function nGetOverviewAccounts()
{
$results = Account::where('archive', '=', false)->select('id', 'display_name', 'server_ip_address', 'server_password', 'status_type_id', 'account_type_id')->get()->toArray();
$accounts = [];
foreach($results as $key => $result)
{
$accountType = AccountType::where('id', $result['account_type_id'])->select('name')->get()->toArray();
$statusType = StatusType::where('id', $result['status_type_id'])->select('name')->get()->toArray();
if(!empty( $accountType[0]['name'])) && !empty( $statusType[0]['name'])){
$accounts[$key]['account_type'] = $accountType[0]['name']; //this doesnt..
$accounts[$key]['status_type'] = $statusType[0]['name'];
}
}
return $accounts;
}
Also if you want the first key of $accountType and $statusType then you can use first() instead of get(). If your keys are different then you can use the $index
Adding some checks never hurt anyone:
public function nGetOverviewAccounts() {
$results = Account::where('archive', '=', false)->select('id', 'display_name', 'server_ip_address', 'server_password', 'status_type_id', 'account_type_id')->get()->toArray();
$index = 0;
$accounts = [];
foreach($results as $result)
{
$accountType = AccountType::where('id', $result['account_type_id'])->select('name')->get()->toArray();
$statusType = StatusType::where('id', $result['status_type_id'])->select('name')->get()->toArray();
$accounts[$index]['account_type'] = (isset($accountType[0]) && isset($accountType[0]['name'])?$accountType[0]['name']:"Unknown";
$accounts[$index]['status_type'] = (isset($statusType[0]) && isset($statusType[0]['name'])?$statusType[0]['name']:"Unknown";
$index++;
}
return $accounts;
}
The problem is your "debug" code only checked if it was working for the 1st iteration of the loop, it may still have not been working for the Nth element.
However if this does fix your problem the next question is why are there accounts associated with invalid account type ids. This may be a symptom of a larger problem.

PHP setting variable as string and then using it again

Could anyone help me with such issue:
I'm trying to make thing, that based on $_Post data I'm showing or not data in the Google tables. (I've removed unnecessary parts of code, that are not actual to this question)
currently, check looks like:
if(!empty($_POST['include_pm'])) {
$pm_script = "data.addColumn('string', 'PM');";
$t0 = ",'\".";
$t1 = '$row['."'".PM."'".']';
$t2 = ".\"'";
$pm_ent = $t0.$t1.$t2;
}
else
{
$pm = "";
$pm_script = "";
$pm_ent = "";
}
And in google visualization table it goes as :
<?php echo $pm_script; ?>
data.addRows([
<?php
foreach ($rows as $row) {
echo "['".$row['TYPE']."'".$pm_ent."],";
}
?>
]);
So basically, when $_POST is empty, nothing is included (as well in script), and it works pretty fine, as needed.
But I'm not able to make it work, when $_POST is not empty: as far as I was experimenting(this one is my last attempt), it printed in the data table exactly string value of the pm_ent value, so it wasn't working in the code as such but became really as a string.
Maybe someone could help me with this, so it would work dynamically - If it's not empty, PM row would be added to the data Rows? As I'm not so good at PHP, I'm having lack of knowledge, how to solve this...
Or maybe there is some smarter way how to do it?
$pm_script = "";
if(!empty($_POST['include_pm'])) {
$pm_script = "data.addColumn('string', 'PM');";
}
And in google visualization table it goes as :
<?php echo $pm_script; ?>
data.addRows([
<?php
foreach ($rows as $row) {
$pm_ent = "";
if( $pm_script !="")
{
$pm_ent =",'".$row['PM']."'";
}
echo "['".$row['TYPE']."'".$pm_ent."],";
}
?>
]);
Hope it will help..

Multi-dimensional array search to preserve parent

TL;DR
I have this data: var_export and print_r.
And I need to narrow it down to: http://pastebin.com/EqwgpgAP ($data['Stock Information:'][0][0]);
How would one achieve it? (dynamically)
I'm working with vTiger 5.4.0 CRM and am looking to implement a function that would return a particular field information based on search criteria.
Well, vTiger is pretty weakly written system, looks and feels old, everything comes out from hundreds of tables with multiple joins (that's actually not that bad) etc., but job is job.
The need arose from getting usageunit picklist from Products module, Stock Information block.
Since there is no such function as getField();, I am looking forward to filter it out from Blocks, that is actually gathering the information about fields also.
getBlocks(); then calls something close to getFields();, that again something close to getValues(); and so on.
So...
$focus = new $currentModule(); // Products
$displayView = getView($focus->mode);
$productsBlocks = getBlocks($currentModule, $displayView, $focus->mode, $focus->column_fields); // in theory, $focus->column_fields should/could be narrowed down to my specific field, but vTiger doesn't work that way
echo "<pre>"; print_r($productsBlocks); echo "</pre>"; // = http://pastebin.com/3iTDUUgw (huge dump)
As you can see, the array under the key [Stock Information:], that actually comes out from translations (yada, yada...), under [0][0] contains information for usageunit.
Now, I was trying to array_filter(); the data out from there, but only thing I've managed to get is $productsBlocks stripped down to only contain [Stock Information:] with all the data:
$getUsageUnit = function($value) use (&$getUsageUnit) {
if(is_array($value)) return array_filter($value, $getUsageUnit);
if($value == 'usageunit') return true;
};
$productsUsageUnit = array_filter($productsBlocks, $getUsageUnit);
echo "<pre>"; print_r($productsUsageUnit); echo "</pre>"; // = http://pastebin.com/LU6VRC4h (not that huge of a dump)
And, the result I'm looking forward to is http://pastebin.com/EqwgpgAP, that I've manually got by print_r($productsUsageUnit['Stock Information:'][0][0]);.
How do I achieve this? (dynamically...)
function helper($data, $query) {
$result = array();
$search = function ($data, &$stack) use(&$search, $query) {
foreach ($data as $entry) {
if (is_array($entry) && $search($entry, $stack) || $entry === $query) {
$stack[] = $entry;
return true;
}
}
return false;
};
foreach ($data as $sub) {
$parentStack = array();
if ($search($sub, $parentStack)) {
$result[] = $parentStack[sizeof($parentStack) - 2];
}
}
return $result;
}
$node = helper($data, 'usageunit');
print_r($node);

Output a result of an SQL query to a PHP array

I'm new to OOP in PHP, is that to seems correct ?
class whatever {
Function Maths() {
$this->sql->query($requete);
$i = 0;
while($val = mysql_fetch_array($this)) {
$tab[i][average] = $val['average'];
$tab[i][randomData] = $val['sum'];
$i=$i+1;
}
return $tab;
}
I want to access the data contained in the array
$foo = new whatever();
$foo->Maths();
for ($i, $i <= endOfTheArray; i++) {
echo Maths->tab[i][average];
echo Maths->tab[i][randomData];
}
Thank you ;)
EDIT: i want to output the result of the SQL query as an array, so i can access it from outside the class
In the interest of helping you out, here are some modifications. Please hear this, though: a lot of this might not make sense without a good background in PHP or OOP in general. You should look at #webbiedave's link.
class whatever {
static function maths() {
$tabs = array();
$results = $this->sql->query($requete);
while($val = mysql_fetch_array($this)) {
$tabs = $val;
}
return $tabs;
}
This fixes syntax errors and logic errors (for instance, the creation of the $results variable to hold the SQL query run).
I made the maths method static, since there's really no need to instantiate a whatever() object with this current example.
Here are some modifications to how this would be used:
$results = whatever::maths();
foreacho ($results as $result) {
echo $result['average'];
echo $result['randomData'];
}
Since maths() returns something, you need to store that in a variable; simply calling it, as you did previously, doesn't do anything.
That convoluted for loop can be replaced with a foreach loop.
Please check out PHP OOP basics:
http://www.php.net/manual/en/language.oop5.basic.php
Edit: Thanks for cleaning up the code. Try something along the lines of:
$tabs = array();
while($val = mysql_fetch_assoc($result)) {
$tabs[] = $val;
}
And:
$foo = new whatever();
$tabs = $foo->Maths();
for ($tabs as $tab) {
echo $tab['average'];
echo $tab['randomData'];
}
http://www.php.net/manual/en/language.oop5.basic.php

Categories