I'm not sure what is going on here, but I'm trying to retrieve some budgets from a modx/xpdo object and getting unexpected results. From the code below, both foreach loops return the same results [that of the first getMany call. 2 items] if I switch the order of the getmany calls I get only one result for both foreach loops.
$tipa = $this->modx->getObject('Tipa', array('id' => $id, 'token' => $token));
// should retrieve two objects
$tipa_sub_budgets = $tipa->getMany('TipaBudget', array('budget_type_id:!=' => '999'));
foreach($tipa_sub_budgets as $sb){
echo $sb->get('id');
}
// should retrieve one object
$tipa_primary_budgets = $tipa->getMany('TipaBudget', array('budget_type_id' => '999'));
foreach($tipa_primary_budgets as $tb){
echo $tb->get('id');
}
I'm not sure what is happening here. What is the correct way to grab 2 sets of objects from the $tipa object?
I think whereas xPDO::getObject() can be passed the criteria either as an array or an instance of xPDOCriteria, xPDOObject::getMany() expects only an instance of xPDOCriteria meaning the array will not work.
Try passing an instance of xPDOCriteria like so...
$criteria = $this->modx->newQuery("TipdaBudget"); // classname, not the alias
$criteria->where(array("budget_type_id:!=" => 999));
$tipa_sub_budgets = $tipa->getMany("TipaBudget", $criteria);
Related
I have a PHP script that gathers data from MongoDB and prints it. Some options are gathered from $_POST supergoblal. Everything works fine but I can't limit the fields to return using an array.
$results = $db->$table->find($param); //This line works and returns all fields
$results = $db->$table->find($param, array('Descripción','Ocurrencias relacionadas'));//This line works and limit the returned fields to the ones specified.
The following code constructs an array to use as a field limiter parameter:
$fields=implode(',', $_POST[field]);
$fd = array($fields);
print_r($fd) shows:
Array ( [0] => 'Descripción','Ocurrencias relacionadas' )
$results = $db->$table->find($param,$fd);` //This line works and returns all documents but only _id field.
Any ideas? It's driving me mad!
Thanks in advance.
You are running your query in the wrong way. First of all, you don't show what $param is, but let's assume it is a query like:
$param = array( 'field1' => 'foo' );
Then as second argument you pass in an array with two values, but that is not what this method wants. The second argument is an array of fields to return, in the following format:
array( 'Descripción' => 1, 'Ocurrencias relacionadas' => 1 );
You pass in the following:
array( 0 => 'Descripción', 1 => 'Ocurrencias relacionadas');
Which means to only show the fields with the names 0 and 1 (which likely don't exist). The _id field is always return so that's why it shows up.
What you need to do, is to pass in the field names as keys in the second argument to find():
$fields=implode(',', $_POST[field]);
$fd = array($fields);
$fd = array_flip($fd); // << important to make the values keys and they keys values: php.net/array_flip
$results = $db->$table->find($param, $fd);
I'm able to query my dynamodb tables, but I only want to retrieve the actual value. I don't want the formatting output. This same question has been answered here for Java, but I'm looking for the PHP solution:
Retrieving just the item value from a dynamodb table?
Here is my getitem query:
$response = $dynamodb->getItem(array(
"TableName" => $tableName,
"ConsistentRead" => true,
"Key" => array(
"userguid" => array(Type::STRING => $userguid)
),
"AttributesToGet" => array("token")
));
print_r($response["Item"]["token"]);
Here is the output:
Array
(
[S] => 9d194513
)
All I want to get back is:
9d194513
I assumed the logical answer would be to change the last line to:
print_r($response["Item"]["token"]["S"]);
But then my code doesn't return anything at all. Obviously still learning PHP here, and any help would be appreciated.
Don't use print_r function, just either echo your variables
echo $response["Item"]["token"]["S"];
or store in a variable for later use
$res_token = $response["Item"]["token"]["S"];
You can also use the getPath convenience method built into the Model object that the SDK returns for operations.
echo $response->getPath('Item/token/S');
For more information about working with responses in the SDK, see the Response Models page in the AWS SDK for PHP User Guide.
Though it's an old question but for anyone coming to this page for seeking answer, this is how I have done it.
getItem returns a Resultobject. You can call the get() function of the SDK, which will give you an array containing the exact value.
$params = [
"TableName" => "EpgApiAccessCount",
"Key" => $this->marshalJson('
{
"ApiUserKey": "' . $apiUserkey . '"
}
')
];
$result = $this->client->getitem($params);
if (!$result instanceof ResultInterface) {
return 0;
}
$item = $this->unmarshalItem($result->get("Item"));
return $item["AccessCount"];
Of course your value and table name will be different, and you can print or do anything else with the value.
I am trying to come up with a means of working with what could potentially be very large array sets. What I am doing is working with the facebook graph api.
So when a user signs up for a service that I am building, I store their facebook id in a table in my service. The point of this is to allow a user who signs up for my service to find friends of their's who are on facebook and have also signed up through my service to find one another easier.
What I am trying to do currently is take the object that the facebook api returns for the /me/friends data and pass that to a function that I have building a query to my DB for the ID's found in the FB data which works fine. Also while this whole bit is going on I have an array of just facebook id's building up so I can use them in an in_array scenario. As my query only returns facebook id's found matching
While this data is looping through itself to create the query I also update the object to contain one more key/value pair per item on the list which is "are_friends"=> false So far to this point it all works smooth and relatively fast, and I have my query results. Which I am looping over.
So I am at a part where I want to avoid having a loop within a loop. This is where the in_array() bit comes in. Since I created the array of stored fb id's I can now loop over my results to see if there's a match, and in that event I want to take the original object that I appended 'are_friends'=>false to and change the ones in that set that match to "true" instead of false. I just can't think of a good way without looping over the original array inside the loop that is the results array.
So I am hoping someone can help me come up with a solution here without that secondary loop
The array up to this point that starts off as the original looks like
Array(
[data](
[0] => array(
are_fb_friends => false
name => user name
id => 1000
)
[1] => array(
are_fb_friends => false
name => user name
id => 2000
)
[2] => array(
are_fb_friends => false
name => user name
id => 3000
)
)
)
As per request
This is my current code logic, that I am attempting to describe above..
public function fromFB($arr = array())
{
$new_arr = array();
if((is_array($arr))&&(count($arr) > 0))
{
$this->db->select()->from(MEMB_BASIC);
$first_pass = 0;
for($i=0;$i < count($arr);$i++)
{
$arr[$i]['are_fb_friends'] = "false";
$new_arr[] = $arr[$i]['id'];
if($first_pass == 0)
{
$this->db->where('facebookID', $arr[$i]['id']);
}
else
{
$this->db->or_where('facebookID', $arr[$i]['id']);
}
$first_pass++;
}
$this->db->limit(count($arr));
$query = $this->db->get();
if($query->num_rows() > 0)
{
$result = $query->result();
foreach($result as $row)
{
if(in_array($row->facebookID, $new_arr))
{
array_keys($arr, "blue");
}
}
}
}
return $arr;
}
To search a value and get its key in an array, you can use the array_search function which returns the key of the element.
$found_key = array_search($needle, $array);
For multidimensional array search in PHP look at https://stackoverflow.com/a/8102246/648044.
If you're worried about optimization I think you have to try using a query on a database (with proper indexing).
By the way, are you using the Facebook Query Language? If not give it a try, it's useful.
I am using Doctrine in my PHP app to return a result set using the following code
$dm = $this->get('doctrine.odm.mongodb.document_manager');
$query = $dm->createQueryBuilder('SomeBundle:Listing')
->select('title')
->field('userId')->equals(1);
$listings = $query->getQuery()->execute();
$listings_array = $listings->toArray(); <--- WHY NOT RETURNING AN ARRAY?????
$data = array('success'=>true,'listings' => $listings_array, 'displaymessage' => $classifieds->count(). " Listings Found");
What gets out out is the following:
{"success":true,"listings":{"50831582253b4acf09000000":{"id":"50831582253b4acf09000000","title":"fddfds","assets":[],"discussions":[]}},"displaymessage":"1 Listings Found"}
I am wanting an array and not a dictionary.
Any help?
I havent messed with the ODM much but i suspect Doctrine always uses the key for the record as the key in the array when calling toArray on a collection, it makes it easier for most of the cases when you would want to do this, especially since there is no distinction in php between a dict/hash and an array.
Call array_values on it if you want a numerically indexed array.
$data = array(
'success'=>true,
'listings' => array_values($listings_array),
'displaymessage' => $classifieds->count(). " Listings Found"
);
Assume the following association among three tables in a database:
//working with three tables a client 'has one' business
//and a business has many business hours.
The following would give us an array of Activerecord objects:
$this->client->business->businesshours
and we would have to pull an object form the array to get its column value:
$this->client->business->businesshours[0]->start_time
Since I am new to PHP Activerecord, what are some ways of proceeding to pull/sort/use information from an array of objects other than looping with a foreach() loop? Are there methods to sort through the array of objects, pull information based on a column value, any best practices?
There is not a library-specific practice for sorting or pulling certain businesshour objects out of the result array. If you want to manipulate the returned array of objects you need to use standard PHP array functions like array_map on the result array.
If you know the sort order or the conditions you want for the returned objects in the result array you should instead specify these in your association declaration so you don't return objects that you don't want or need.
Since you haven't posted any code you'll just have to extrapolate to your own situation from this example:
static $has_many = array(
array(
'businesshours',
'conditions' => array('hour BETWEEN ? AND ?' => array(9, 17)),
'order' => 'hour ASC'
)
);
This association declaration will return only the businesshour objects between 9 and 17 and do it in ascending order. So as you can see, if you constrain your associations to only the records you need, there will be no need to sort or parse the result array once received.
Sometimes it's useful to use array_map to get only certain objects from your result array:
// get $result array
$new = array_map(function($obj) { if ($obj->hour > 9){ return $obj; } }, $result);