I’m trying to handle the contents of an array in WordPress, before I store the array within a session the array outputs as follows;
Array
(
[0] => yes
[1] => no
)
However after storing in $wp_session[‘test_array’] it outputs like;
Recursive_ArrayAccess Object
(
[container:protected] => Array
(
[0] => yes
[1] => no
)
[dirty:protected] => 1
)
Is there any advise on returning the array to it’s original format so I can handle it easily.
Cheers for any help
You can do it by serialize() the array before you store it and unserialize() it when you retrieve it.
For Example:
$wp_session['test_array'] = serialize( array( 'yes', 'no' ) );
$test_array = unserialize( $wp_session['test_array'] );
print_r( $test_array );
How can i get the first smarty array element ?
Actually i know how to do this... but i have following issue.
I get a array passed that looks like this
[DATA] => Array
(
[12] => Array
(
[content] => foobar
)
[1] => Array
(
[content] =>
)
[2] => Array
(
[content] =>
)
[3] => Array
(
[content] =>
)
//this is a snipit of {$myVar|#print_r}
this goes down until [11]
For some reason there is no [0] and a [12] at this position.
I don't know if this will allways be 12 but I know it allways be at the first position.
I can't sort this array because there is another array that has the same sortorder and I have to keep this order for later output.
Is there a way to select the first element without using array[0] or array.0 ?
Info: The project im working on uses Smarty 2
EDIT
I would re-index the array if i knew how :)
Since there is now answere after a couple of hours, i solved my problem temporarly.
To solve this, I opened {php} in smarty, got the array I need, splitted it into two arrays (re-indexing them of course so it starts at 0). Than I temp-save pos 0 from each array to a temp array. Override the orig 0 with underscore (_) and than multisort them, put back the original value to 0 and pass them back to $this->_tpl_vars very complicated way. (all inside the tpl)
{php}
// get array data and re-index it
$i=0;
foreach( $this->_tpl_vars['options'] as $option )
{
foreach( $option['DATA'] as $data )
$array[$i][] = $data;
$i++;
}
//delete empty entrys
$i=0;
foreach( $array[1] as $data ){
if(trim($data['content']) != ""){
$s[] = $array[0][$i];
$a[] = $array[1][$i];
}
$i++;
}
//temp save first values
$tmp_s = $s[0];
$tmp_a = $a[0];
//override first values to have a clean sort and keep them values on pos 0
$s[0] = $a[0] = "_";
//sort the arrays
array_multisort($s,$a);
//putting back the original values
$s[0] = $tmp_s;
$a[0] = $tmp_a;
//pass the array back to tpl_vars
$this->_tpl_vars['new_options'][] = $s;
$this->_tpl_vars['new_options'][] = $a;
{/php}
IF in PHP you have:
$smarty->assign(
'myVar',
array('DATA' =>
array(
12 => array('content' => 'first element'),
1 => array('content' => 'second element')
))
);
In Smarty you can use:
{assign var=first value = $myVar.DATA|#key}
{$myVar.DATA.$first.content}
And you will get displayed:
first element
However if in PHP you use:
$data = array(
12 => array('content' => 'first element'),
1 => array('content' => 'second element')
);
next($data);
$smarty->assign(
'myVar',
array('DATA' => $data
)
);
And in Smarty have the same as I showed at the beginning, the result will be:
second element
You would need to call:
reset($data);
after
next($data);
I think you cannot call reset for array in Smarty but I could be wrong.
It's also possible to reset array in Smarty but it's not so easy.
If in PHP you have:
$data = array(
12 => array('content' => 'first element'),
1 => array('content' => 'second element')
);
next($data);
$smarty->assign(
'myVar',
array('DATA' => $data
)
);
In Smarty you could use:
{assign var=$myVar.DATA value=$myVar.DATA|#reset}
{assign var=first value = $myVar.DATA|#key}
{$myVar.DATA.$first.content}
And you will get:
first element
as result
If your data is in array {$data} then using Smarty 3 you can just
{$firstData = $data|reset}
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'm trying to build an array and update a few fields in a loop.
This is my request->data
Array
(
[list] => Array
(
[4] => null
[2] => null
[3] => null
[5] => 3
)
)
It's the return value from a jquery serialized list. The key being the row id and the value being the rows parent_id.
So I loop through the array in the controller:
foreach ($this->request->data['list'] as $key => $value) {
(!isset($orders[$value])) ? $orders[$value]=0 : $orders[$value]++;
$data = array('id' => $key, 'parent_id' => (int)$value, 'display_order' => $orders[$value]);
$this->Category->save($data);
}
The $data array that I create in the loop is correct but the sql logs only shows SELECT COUNT(*) etc. for each row and no UPDATE commands.
I have tried all manner of ways to save this: using set() method, using $this->Category->id = $key; instead of directly adding the key in the data array.
Any ideas why this is not saving? I'm sure it is something simple...
i think u forgot the cake convention in the save method, you have to put all the field values inside an array with the Model name FirstCap too, something like this:
Array
(
[ModelName] => Array
(
[fieldname1] => 'value'
[fieldname2] => 'value'
)
)
Else you can use set for each and every value, and also youre forgetting to create one row for every insert youre making so try something like this:
foreach ($this->request->data['list'] as $key => $value) {
(!isset($orders[$value])) ? $orders[$value]=0 : $orders[$value]++;
$data = array( 'Category' => array('id' => $key, 'parent_id' => (int)$value, 'display_order' => $orders[$value]));
$this->Category->save($data);
}
Also you can set each and every id and then iterates over the values
foreach ($this->request->data['list'] as $key => $value) {
(!isset($orders[$value])) ? $orders[$value]=0 : $orders[$value]++;
$this->Category->id = $key;
$this->Category->set(array('parent_id' => (int)$value,
'display_order' => $orders[$value]
));
$this->Category->save();
}
try each and every answer but i think the last one will fit better at your problem.
From the CakePHP book.
When calling save in a loop, don’t forget to call create().
echo $data and match it with save() method's syntax.also do not slip to match data types of fields in table.
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