DQL query for getting specific columns from the table - arrays

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.

Related

Laravel 4 updating all records with array gives me parameter mismatch error

Trying to update each row of a table with a multidimensional array created from querying another database.
The array:
Array
(
[0] => Array
(
[community_id] => ap
[floorplan_code] => ap1-1a
[name] => 33flat
[hidden] => 0
)
[1] => Array
(
[community_id] => ap...
Here is the code I'm using in an attempt to update:
$floorPlan = new Floorplan; //create new instance
$floorPlan->get(); //get all rows
$floorPlan->update($floorplanMappedArray); //map db columns to array and update
Error message: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array.
The parameter mismatch came from the fact that I was trying to shove a multidimensional array into a single row. Therefore, I needed a foreach loop to index through the multidimensional array.
I thought that there was a magical way to use the update() method in the same way that the insert() method is used. Apparently, there is not.
Here is the code that solved the parameter mismatch error:
foreach ($floorplanMappedArray as $floorPlan) {
Floorplan::where('floorplan_code', $floorPlan['floorplan_code'])->update($floorPlan);
}

Cakephp How to set find() to return blank array instead of empty array when no result matched

By default , cakephp would return empty array on find() when nothing founded.
but how to set it to show as blank array.
For example:
$customer = $this->Transaction->Customer->find(--conditions to return 0 result.--)
I want it to show as blank array like this.
array('Customer' => array('customer_id'=>null, 'name'=>null, 'lastname'=>null))
not just empty one like
array() or null
because I always got error shown in view that $customer['Customer']['name'] is undefined index. and I don't like to use isset() or is_null() to check before every time.
Use the afterFind callback method in your model. Something like this:
public function afterFind($results, $primary = false) {
if (empty($results)) {
$results = array('Customer' => array('customer_id'=>null, 'name'=>null, 'lastname'=>null))
}
return $results;
}
http://book.cakephp.org/2.0/en/models/callback-methods.html
If you really want/need to do this, you can use something like:
$default = array('Customer' => array('customer_id' => null, 'name'=>null, 'lastname' => null));
$customer = $this->Transaction->Customer->find(...)
$customer = array_merge($default, $customer);
This way, if the result is empty, it will use your default values.
However, this is not a good practice, because you might end up displaying "Welcome, NULL", in the page. You should use if (!empty($customer)) ... in your view.
Also, in this example, are you using find->('first') ?

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.

PHP query -- Returned array values

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

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