PHP query -- Returned array values - arrays

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);

Related

cakephp pagination set condistion from array

I am using a form with several check boxes i need to display only those data which is in check box category.
How to write conditions for that.
for($i=0;$i<count($this->request->data['filter']['delivering']);$i++)
{
$opt1=".'Gig.bangsalsodeliverings' => ".$this->request->data['filter']['delivering'][$i];
$opt2=$opt2.$opt1.',';
}
$options=array('conditions' => array($opt2));
$this->Paginator->settings = $options;
$agetGigsItem = $this->Paginator->paginate('Gig');
But getting error.
Thanks in advance
It seems you're using a string contatenation instead of array to build the conditions array.
Also it's not clear to me if the filter delivering is a set of strings or integers.
I guess you can try:
// Merge the filters into a csv string
$filters = array();
foreach($this->request->data['filter']['delivering'] as $v){
$filters[] = "'{$v}'";
}
$csv_filters = implode(",", $filters);
// Use the csv to make a IN condition
$this->Paginator->settings = array('conditions' => array(
"Gig.bangsasodeliverings IN ({$csv_filters})",
));
Please note that sql injection can be made here, so prepare your data before creating $csv_filters.

Cakephp value from array

I've read many similar topics here but not one helps me with problem.
i'm trying to get sections_id value from query in controller.
$query_id = "SELECT sections_id FROM sections WHERE name='".$table_name."'";
debug($id = $this->Info->query($query_id)); die();
there is debug result
array(
(int) 0 => array(
'sections' => array(
'sections_id' => '14'
)
)
)
and i tried in controller get value of id typing $id['sections']['sections_id'], or
$id['sections_id'] and many other types, nothing works. Do you have any idea ?
use $id[0]['sections']['sections_id'] to access it
For one result use
$data[0]['sections']['sections_id']
If query returns more than one result the use below code:
foreach($id as $data){
echo $data['sections']['sections_id']
}
Look for array index's carefully! Iinjoy

what it the find list error

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.

DQL query for getting specific columns from the table

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.

Unsetting elements of a cakephp generated array

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

Resources