I am looking to except single element from array. My array is:
Array
(
[0] => Array
(
[0] => Array
(
[COUNT(ID)] => 0
)
)
)
I have already use PHP functions basename and array_shift, but they didn't give me proper value. I want only single string COUNT(ID) value.
Here is my function using in cakephp model:
$res = $this->query("select COUNT(ID) from users where Username = '".$Username['Username']."'");
if ($res[0][0]['COUNT(ID)'] >= 1)
{
return false;
}
else
{
return true;
}
I don't need $res[0][0], I need only COUNT[ID]. Is there any easy way to find only COUNT[ID].
If you are using CakePHP, it's good to use model and inbuilt functions to get answer what you want...
$this->loadModel('User'); //If you are in controller
$total = $this->User->find('count', array(
'conditions' => array('Username' => $Username['Username'])
));
You'll get answer in single variable..!!
Your output is produced by code like this
$data = array(
array(
array(
'COUNT(ID)' => 0
)
)
);
You can access its value by calling directly
$data[0][0]['COUNT(ID)']
This could be wrong problem you are solving, as it seems like database query result that should not look like that and could be done with more ease. You should show your original function/problem, that this script is part of.
Let's say you array's name is $myArray, than you can assign the value of $myArray[0][0]['COUNT(ID)'] to $value in the way you usually assign a value: $value = $myArray[0][0]['COUNT(ID)'];.
If you want to delete an index from an array, use unset() like this: unset($myArray[0][0]['COUNT(ID)']). I hope this answers your question.
If you know the exact count of nesting in array you can just access it with indexes
$array[0][0]['COUNT(ID)']
If no, you might want to use the function which will recursively find you the first nested element that is not an array
function getStringFromArray($array) {
if (is_array($array)) {
foreach ($array as $key => $value) {
if (is_array($value)) {
return getStringFromArray($value);
} else {
return $value;
}
}
} else {
throw new Exception("Not an array given");
}
}
If you are sure that array structure will remain same then this could be useful :-
function array_values_recursive($ary)
{
$lst = array();
foreach( array_keys($ary) as $k ){
$v = $ary[$k];
if (is_scalar($v)) {
$lst[] = $v;
} elseif (is_array($v)) {
$lst = array_merge( $lst,
array_values_recursive($v)
);
}
}
return $lst;
}
$arr=array(array(array('COUNT(ID)'=>5)));
$res=array_values_recursive($arr);
echo '<pre>';print_r($res);
output :-
Array
(
[0] => 5
)
You can probably fetch it by associative array to reduce dimension but you can remove index. May be you can use foreach to automatically use indexs.
Try this code:
public $uses = array('User');
$count = $this->User->find('count', array(
'conditions' => array('Username' => $Username['Username'])
));
if ($count >= 1) {
return false;
} else {
return true;
}
You can use following technique for your solution. i did not get you what you want to do with your array but you can try below solution
$arr = Set::extract("/0/COUNT(ID)",$data);
where $data is your input array.
you will get following output
Array
(
[0] => 5
)
you can refer below link
Remove array key from array in cakephp
Related
I am getting an error on line 10 :
Call to a member function getUserId() on a non-object in
/** #var $users User*/
$users= $this->getRepository("repo")->findAll();
$response = array();
foreach ($users $user) {
$response[] = array(
**line10 'user_id' => $user->getUserId()
);
}
basicly in line 10 it did not recognize the call to getUserId
so how could I fetch the data to array or json ?
thanks
Inside your loop on $campaigns, one of the elements of the array seem to be null, so this element does not have the method getUserId. Try to var_dump your $campaigns array to check its content, I'm pretty sure you would be able to find the mistake after that.
Try: $campaigns = $this->getDoctrine->getRepository("repo")->findAll();
Looks like $campaigns have no results, try:
if($capaigns) {
foreach ($campaigns as $user) {
$response[] = array('user_id' => $user->getUserId());
}
}
Its a very basic php question, I want to display a value with comma separated from.I know a procedure,I can get comma separated value by using comma explode. I just want to confirm will it run successfully or not.I am giving my output and array below : I need my output something like Sahbaj,test-name.
And my array :
Array
(
[0] => Array
(
[AdoPosition] => Array
(
[name] => Sahbaj
)
)
[1] => Array
(
[AdoPosition] => Array
(
[name] => test-name
)
)
)
My controller code is below :
$name = $this->AdoPosition->find('all',
array(
'fields'=>'AdoPosition.name',
'group'=>'AdoPosition.name'
));
pr($name);
Do that:
$name = $this->AdoPosition->find('list', array(
'fields' => array('AdoPosition.name', 'AdoPosition.name'),
'group' => array('AdoPosition.name')
));
$name = implode(',', $name);
The return is:
"Sahbaj,test-name"
make it simple
$names=Set::extract("/AdoPosition/name",$array);
OR
$names = $this->AdoPosition->find('list', array('fields'=>array('name')));
look at this.
Remove array key from array in cakephp
Another alternative is to ask mysql to join with comma like-
$data = $this->AdoPosition->query('SELECT GROUP_CONCAT(DISTINCT name) from your_table_name;');
For better efficiency try this.
$result = implode( ",", Set::classicExtract($name, '{n}.AdoPosition.name'));
echo $result; // Sahbaj,test-name
I am creating a custom datasource and I am having problems when i request find('list'). find('all') returns perfectly what I want within my controller but find('list') just returns an empty array.
The funny thing is if I do a die(Debug($results)) in the datasource within the read function then I get my find('list') array correctly but if I return it i then get an empty array in my controller. Any ideas?
Code below:
public function read(Model $model, $queryData = array(), $recursive = null) {
if ($queryData['fields'] == 'COUNT') {
return array(array(array('count' => 1)));
}
$this->modelAlias = $model->alias;
$this->suffix = str_replace('Flexipay', '', $model->alias);
if(empty($model->id)){
$this->url = sprintf('%s%s%s', $this->sourceUrl, 'getAll', Inflector::pluralize($this->suffix));
}
$r = $this->Http->get($this->url, $this->config);
if($r->isOk()){
$results_src = json_decode($r->body, true);
if(is_array($results_src)){
//$this->find('list');
if($model->findQueryType == 'list'){
return $this->findList($queryData, $recursive, $results_src);
}
//$this->find('all');
foreach($results_src['PortalMandantenResponses']['portalMandantenResponses'] as $r){
$results[] = $r;
}
if(!empty($results)){
$e = array($model->alias => $results);
return $e;
}
}
}else{
//
}
return false;
}
My response from die(debug(array($model->alias => $results);
(int) 0 => array(
'Mandant' => array(
'ns2.id' => (int) 79129,
'ns2.name' => 'company a'
)
),
(int) 1 => array(
'Mandant' => array(
'ns2.id' => (int) 70000,
'ns2.name' => 'company b'
)
),
Controller Code is here:
public function test2(){
//$a = $this->User->find('list');
//die(debug($a));
$this->loadModel('Pay.Mandant');
$a = $this->Mandant->find('list', array('fields' => array('ns2.systembenutzernr', 'ns2.systembenutzernrBezeichnung')));
die(debug($a));
}
use,
$a = $this->Mandant->find('list', array('fields' => array('ns2.systembenutzernr', 'ns2.systembenutzernrBezeichnung')));
$this->set(compact('a'));
You can use $a for the dropdown creation in view file.
I just had the same problem writing my custom model though I don't know if the cause in your case is the same, though you should probably look in the same place.
in Model.php there is a function _findList($state, $query, $results), my issue was the fields you specify in the find() call must match the $results structure exactly, otherwise at the end of the _findList() function the call to:
Hash::combine($results, $query['list']['keyPath'], $query['list']['valuePath'], $query['list']['groupPath'])
returns the empty array. The keyPath of {n}.MODELNAME.id, etc must match the name of the model specified in $results, for example
[0] => ['MODELNAME'] = array()
[1] => ['MODELNAME'] = array()
In my case my keyPath and valuePath had a different value for MODELNAME than in the results array
Hope that helps
I currently have index, view, add and edit from my tickets/views and am planning to add another view called current. I want to display only the "Resolved" tickets on that view but have no idea how to do it. I've been trying to figure this out for the past couple of days with no luck. Where should I put the "find" code and what should I include on my tickets/current view code? Here's what I have tried so far:
/controllers/tickets_controller
function current() {
$current = $this->set('tickets', $this->Ticket->find('all', array(
'conditions' => array('Ticket.status' => 'Resolved'),
'order' => array('Ticket.created' => 'desc')
)));
$this->set('tickets', $this->paginate());
}
/views/tickets/current.ctp
<?php
$i = 0;
foreach ($tickets as $ticket):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
?>
This code displays the same as /views/tickets/index.ctp (with all the records from the table).
Thanks,
Lyman
You were almost there. $this->set('foo') in Cake is one way you can pass variables to the view.
What the code below does is set a variable called current the return value of the find method which has a custom condition, which can be accessed from the view. (It's an array in this case; but you can set anything)
You don't need the paginate() here unless you plan to use pagination in this view.
So something like this should do the trick ($curr is a bad variable name but I wasn't feeling inventive. (resolved_tickets would make more sense (why current?))
//controllers/tickets_controller
function current() {
$this->set('current', $this->Ticket->find('all',
array('conditions' => array('Ticket.status' => 'Resolved'),
'order' => array('Ticket.created' => 'desc')
)));
}
/views/tickets/current.ctp
<?php
$i = 0;
// adjust the variable in the foreach
foreach ($current as $curr):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
echo $curr['Ticket']['id']; // example
?>
How can I convert the result of Trips::model()->findAll() to an array?
I'm going on the assumption here that you only need to retrieve just the bare arrays, and not any associated model objects.
This will do it:
$model = Trips::model();
$trips = $model->getCommandBuilder()
->createFindCommand($model->tableSchema, $model->dbCriteria)
->queryAll();
This is like the Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll(); examples, except:
It'll ask the model for the table name; you won't need to write the table name in both the model and the query.
You can call scoping functions on $model first, eg.
$model = Trips::model()->short()->destination('Austin, TX');
Doing this means you can use the model's existing query shortcuts, instead of putting them in the query directly.
In contrast, the $trips = Trips::model()->findAll(); (using foreach) is a bit wasteful, in that you're pulling the rows from the database, setting up a bunch of objects, and then throwing them all away. It'll work fine for small result sets, but I wouldn't use that if you're looking at a long list of Trips.
Caveat:
If this is just a quick prototype, though, by all means use the createCommand() or findAll()-and-loop examples.
This is the right way to do, it follows Yii conventions
$trips = Trips::model()->findAll();
$arr = array();
foreach($trips as $t)
{
$arr[$t->id] = $t->attributes;
}
This is used when you have complex queries, those you find difficult to create with Yii conventions.
Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll();
For example, when you need to pass all the data from the model to an array. You cannot pass it directly as it does pass some ActiveRecord data information that you don't need.
This is same.
$array = CHtml::listData(Trips::model()->findAll(), 'trip_id', 'trip_name');
Easy and simple way: I use listData() method to make array to dropdown menus, and I think this will help you.. check this example:
code:
<?php
/*you can use here any find method you think
proper to return your data from db*/
$models = Trips::model()->findAll();
// format models resulting using listData
$tripsArray = CHtml::listData($models, 'id', 'name');
print_r($tripsArray);
?>
output:
array(
'1'=>'trip1',
'2'=>'trip2',
'3'=>'trip3',
)
$model = Trips::model()->findAll();
$arr = CHtml::listData($model, 'trip_id', 'trip_name');
var_dump($arr);
CHtml::listData() will return an array value.
You can create collections CMap continue to work with her
$collections = new CMap();
foreach (YourModel::model()->findAll(['index' => 'id']) as $key => $row) {
$collections->add($key,$row->attributes);
}
var_dump($collections ->toArray());
I'm pretty sure you can do this:
$trips = Trips::model()->findAll();
$arr = array();
foreach($trips as $t)
{
$arr[$t->id] = $t->attributes;
}
I'm assuming you have the attribute 'id' as your model's primary key.
i use $array = CJSON::decode(CJSON::encode($model)); to convert $model to $array.
You can use this.
$Trips::model()->findAll(array('index'=>'trip_id'));
if(count($Trips)>0)
{
$TripsArrayList=array();
foreach($Tripsas as $singleTrip)
{
$TripsArrayList[]=array('trip_id'=>$singleTrip->trip_id,'name'=>$singleTrip->name);
}
}
Your output will be
Array
(
[0] => Array
(
[trip_id] => 1
[name] => Nashik
)
[1] => Array
(
[trip_id] => 2
[name] => Puna
)
[2] => Array
(
[trip_id] => 3
[name] => Mumbai
)
)
$cats = Category::model()->findAll();
$count_cats = count($cats);
if($count_cats > 0){
$arr_category = array();
foreach($cats as $cat)
array_push($arr_category,$cat->attributes);
}
print_r($arr_category);
-> result
Array(
[0] => Array
(
[cat_id] => 2
[title] => Đương đại
[title_full] => Đương đại
[desc] =>
[alias] => duong-dai
[p_id] => 0
[type] => 1
[status] => 1
[sort_order] => 2
[selected] => 0
)
[1] => Array
(
[cat_id] => 164
[title] => Nhiệt đới
[title_full] => Nhiệt đới
[desc] =>
[alias] => nhiet-doi
[p_id] => 0
[type] => 1
[status] => 1
[sort_order] => 0
[selected] => 0
)
[...])
Assuming from your question that you want all the attributes, a more compact solution to give you all attributes hashed by id, you can use CActiveRecord's 'attributes' pseudoproperty as follows:
CHtml::listData(Trips::model()->findAll(), 'id', 'attributes')
In yii2 you can use asArray()
$someArray = Sometable::find()->select(['id', 'name', 'role'])->asArray()->all();
Use DAO for arrays
$array = Yii::app()->db->createCommand('SELECT * FROM tbl')->queryAll();
Don't used CHtml::listData for this. It has to be used for other purposes.
There is an index property of CDbCriteria which is suitable for you requirement.
//1st option
Trips::model()->findAll(array('index'=>'trip_id'));
//2nd option
$c = new CDbCriteria();
$c->index = 'trip_id';
Trips::model()->findAll($c);
Use simply:
$trips = Trips::model()->findAll();
$trips_array = CJSON::decode(CJSON::encode($trips));
Note: This is not good way but returns array