I tyed get with the method $this>model->find() an array with ids of my model that have this form:
Array ( [0] => 2, [1] => 3) (value are the IDs)
and I try $this->model->find('list') I thought that would work too but for some strange reason I have done:
$this->model->find('list',array('recursive' => -1 ,'fields' => array('model.type_id'),'conditions'=>$cond));
and the query result is:
SELECT `model`.`round_id`, `model`.`type_id` FROM `database`.`model` AS `X` WHERE `X`.`Round_id` = '1'
If I make this query to the database returns two values but cakephp returns only one:
Array ( [1] => 2 )
i do not know that may be going
I would use
$ids = $this->Model->find('list', array('fields' => array('id')));
if you really need the 0 based integer keys, you can still do:
$ids = array_values($ids);
but that is not necessary IMO.
Update:
After your question update the whole meaning of your question itself changed:
If you specify only id, they keys and values will both be filled with it.
Using 'fields' => array('round_id', 'type_id') you have round_id filling the keys, and type_id filling the values for find(list).
find(list) returns always a list (key + value row). If you don't want that use find(all) then.
Related
I have this sorted array with top 5 products
foreach ($bestsellers as $item) {
$data = json_decode($item->order_details, true);
$product_ids[] = key($data);
}
arsort($product_ids);
$three = array_unique(array_slice($product_ids, 0, 5, true));
print_r($three);
The result is
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
1,2,3,4,5 are products id's. Is it possible to use this values in the query to products table so I can display on page more information about the products. Not just the ID.
Something like
Product::where('product_id', $value);
Update
$best = Product::whereIn('product_id', $three)->get();
foreach($best as $info)
{
dd($info->title);
}
Yes, You should use whereIn for array. In fact, whereIn takes second parameter as array of values for specified column.
Product::whereIn('product_id', $value);
whereIn()
The whereIn method verifies that a given column's value is contained
within the given array:
This should be a simple thing to solve...
I have got these estatements when a user logs in:
$query = $conn->prepare("SELECT * FROM admins WHERE username = :user AND password = :pass");
$query->bindValue(":user", $user);
$query->bindValue(":pass", md5($pass));
$query->execute();
Now if the user exists, I return the user information from the database, but if not, I return false instead...
if($query->rowCount() > 0) {
$admininfo = $query->fetchAll(PDO::FETCH_ASSOC);
} else {
return false;
}
But when I var_dump the variable $admininfo I get an array with a number key before the actual array... like this:
array (size=1)
0 => <---- I DONT KNOW WHERE THIS COME FROM. I USED PDO::FETCH_ASSOC
array (size=9)
'id' => string '1' (length=1)
'username' => string 'admin' (length=5)
'password' => string '21232f297a57a5a743894a0e4a801fc3' (length=32)
'permissionid' => string '1' (length=1)
'name' => string 'Administrador' (length=13)
'lastname' => string 'Softing' (length=7)
'phonenumber' => null
'cellphonenumber' => null
'info' => null
I will put this information inside the SESSION array, so I want to access it by $_SESSION["admininfo"]["username"] or $_SESSION["admininfo"]["phonenumber"]
but I have to put something like this instead: $_SESSION["admininfo"][0]["phonenumber"].
How can I remove that 0 from the keys? Thank you!
According to the documentation for fetchAll, it will return an array of elements. This is because it is getting all of the rows in the table that match your criteria. In your case, you are only getting back one row, located at index 0. If you know you only want one result, use fetch instead of fetchAll. It will get rid of the 0.
You're using fetchAll. This will give you an array of DB rows -- of all the rows that were matched.
Use fetch in a while loop to go through individual rows one by one.
I am using the query function in cake PHP ($this->query(select...)), and I know it returns an array of the values. If the query will only return one value, what is the position of that value in the array?
Would $element = $arrayName(0) be correct?
I'm trying to use it as such:
$flowsheet_name = $this->query("select FLOWSHEET_NAME from FLOWSHEET_TEMPLATE where FLOWSHEET_ID = ".$value.";");
$flowsheet_question = $flowsheet_name(0);
array_push($this->$filedMethodMappings, $flowsheet_question => array(
CaBase::KEY_MAPPING_LOGIC_COMPLEXITY => CaBase::LEVEL3_COMPLEXITY,
CaBase::KEY_FIELD_LOGIC_NAME => 'wsUnifiedKey',
CaBase::KEY_FIELD_QUESTION_ID => ''.$value,
)
);
But I can't tell if it's working. I'm getting a double arrow error here:
$flowsheet_question => array(
In CakePHP, easy way to see what is going on in your array is:
debug($flowsheet_name);
I had created the following table method in order to extract some specific table columns to allow later comparison to values stored on arrays:
public function findAllComposedExcelColumns()
{
$q = Doctrine_Query::create()
->select('p.branch_code, p.state_id, p.state_description, p.account, p.client_name')
->from('Process p');
return ($q->fetchArray());
}
But when I print an element of the retrieved array, it has also the property id which a don't need.
Array ( [0] => Array ( [id] => 1 [branch_code] => ... [state_id] => ... [state_description] => ... [account] => ... [client_name] => ... ) )
Why the id is also appearing on the results? There is any way to remove it?
Try hydrating with HYDRATE_SCALAR - it might give you what you want.
Eg.
public function findAllComposedExcelColumns()
{
$q = Doctrine_Query::create()
->select('p.branch_code, p.state_id, p.state_description, p.account, p.client_name')
->from('Process p');
$output = $q->execute(array(), Doctrine_Core::HYDRATE_SCALAR);
return $output;
}
edit:
note that this will also change your array keys,
eg from ['branch_code'] to ['p_branch_code']
using this type of hydration method is also not ideal when there are related records.
All in all, the above achieves your goal for this scenario. However, I would agree with DrColossos that it is better to simply loop over and ignore the data you don't want.
I have an array called $all_countries following this structure:
Array
(
[0] => Array
(
[countries] => Array
(
[id] => 1
[countryName] => Afghanistan
)
)
[1] => Array
(
[countries] => Array
(
[id] => 2
[countryName] => Andorra
)
)
)
I want to loop through an array called prohibited_countries and unset the entire [countries] element that has a countryName matching.
foreach($prohibited_countries as $country){
//search the $all_countries array for the prohibited country and remove it...
}
Basically I've tried using an array_search() but I can't get my head around it, and I'm pretty sure I could simplify this array beforehand using Set::extract or something?
I'd be really grateful if someone could suggest the best way of doing this, thanks.
Here's an example using array_filter:
$all_countries = ...
$prohibited_countries = array('USA', 'England'); // As an example
$new_countries = array_filter($all_countries, create_function('$record', 'global $prohibited_countries; return !in_array($record["countries"]["countryName"], $prohibited_countries);'));
$new_countries now contains the filtered array
Well first of all id e teh array in the format:
Array(
'Andorra' => 2,
'Afghanistan' => 1
);
Or if you need to have the named keys then i would do:
Array(
'Andorra' => array('countryName'=> 'Andorra', 'id'=>2),
'Afghanistan' => array('countryName'=> 'Afghanistan', 'id'=>1)
);
then i would jsut use an array_diff_keys:
// assuming the restricted and full list are in the same
// array format as outlined above:
$allowedCountries = array_diff_keys($allCountries, $restrictedCountries);
If your restricted countries are just an array of names or ids then you can use array_flip, array_keys, and/or array_fill as necessary to get the values to be the keys for the array_diff_keys operation.
You could also use array_map to do it.
Try something like this (it's probably not the most efficient way, but it should work):
for ($i = count($all_countries) - 1; $i >= 0; $i--) {
if (in_array($all_countries[$i]['countries']['countryName'], $prohibited_countries) {
unset($all_countries[$i]);
}
}
If you wanted to use the Set class included in CakePHP, you could definitely reduce the simplicity of your country array with Set::combine( array(), key, value ). This will reduce the dimensionality (however, you could do this differently as well. It looks like your country array is being created by a Cake model; you could use Model::find( 'list' ) if you don't want the multiple-dimension resultant array... but YMMV).
Anyway, to solve your core problem you should use PHP's built-in array_filter(...) function. Manual page: http://us3.php.net/manual/en/function.array-filter.php
Iterates over each value in the input
array passing them to the callback
function. If the callback function
returns true, the current value from
input is returned into the result
array. Array keys are preserved.
Basically, pass it your country array. Define a callback function that will return true if the argument passed to the callback is not on the list of banned countries.
Note: array_filter will iterate over your array, and is going to be much faster (execution time-wise) than using a for loop, as array_filter is a wrapper to an underlying C function. Most of the time in PHP, you can find a built-in to massage arrays for what you need; and it's usually a good idea to use them, just because of the speed boost.
HTH,
Travis