I want to store multi dimension array in codeigniter userdata session.
when i store a simple array it works fine. but in multi dimension it store nothing. Is there a way to store multi dimension array in session.
My code is:
foreach ($unique_data as $unique_type) {
$indexes = index_unique_values($product_all_data, 'type', $unique_type['type']);
foreach ($indexes as $key) {
$product_name = $product_all_data[$key]['name'];
$product_type = $product_all_data[$key]['type'];
$product_status = $product_all_data[$key]['status'];
$cost = $product_all_data[$key]['cost'];
$price = $product_all_data[$key]['price'];
$barcode = $product_all_data[$key]['barcode'];
$product_type_all_prod[] = array('name' => $product_name, 'type' => $product_type, 'status' => $product_status, 'cost' => $cost, 'price' => $price, 'barcode' => $barcode, 'cat_name' => '');
}
}
$product_bytype_array = array("product_by_type" => $product_type_all_prod);
$this->session->set_userdata($product_bytype_array);
Thank you.
What if you try something like...
$this->session->set_userdata(['product_data' =>$product_bytype_array]);
You can check that you are actually generating an array in the format you are expecting.
Then check that the Stored result is in the format you are expecting.
// What's in the resulting array that we want to store in the session?
var_dump($product_type_all_prod);
$product_bytype_array = array("product_by_type" => $product_type_all_prod);
$this->session->set_userdata($product_bytype_array);
//What's in the array in the session
var_dump($this->session->userdata('product_by_type'));
That should help.
NOTE: I've tested this using CI 3.1.0 with sessions configured as the types File and then as Database.
Related
I passed my formData object via Ajax into laravel controller that have "pic[]" which contain an array of uploaded images, and "desc[]" which contain an array of descriptive text that related to the corresponding index for each image on the pic[] array.
Normally, when I want to insert it into the database, I would do this
if ($request->hasFile('pic')) {
foreach($request->pic as $p)
{
$myRow = tableName::create([
'picture' => $p
]);
};
};
But now that I want to insert the picture description into the same row that I just created, nested loop surely won't work, and I'm not sure how to do it with double loop for the desc array.
If you have desc[] like: [0 => 'First', 1 => 'Second', ...], you can access index of description if is equal to index of picture.
foreach($request->pic as $index => $p)
{
$myRow = tableName::create([
'picture' => $p,
'description' => $request->desc[$index] // also try $request->get('desc.' .$index)
]);
};
I hope it was helpful. Good luck.
Follow this code to insert an image in your database by using ajax
foreach($request->pic as $index => $p)
{
$myRow = tableName::create([
'picture' => $p,
'description' => $request->desc[$index] // also try $request->get('desc.' .$index)
]);
};
I hope it was helpful to you.
My code:
$this->PackageCustomer->id = $customer_id;
$data['PackageCustomer'] = array(
'shipment' => 2,
'comments' => $this->request->data['Ticket']['content'],
'shipment_equipment' => $this->request->data['Ticket']['shipment_equipment'],
'shipment_note' => $this->request->data['Ticket']['shipment_note'],
'issue_id' => $this->request->data['Ticket']['issue_id']
);
pr($data); exit;
$this->PackageCustomer->save($data['PackageCustomer']);
//var_dump($this->PackageCustomer->invalidFields());
// pr($this->PackageCustomer->error);
echo $this->PackageCustomer->getLastQuery(); exit;
I inspect array $data. Data is being revived properly. And getLastQuery function is:
function getLastQuery() {
$dbo = $this->getDatasource();
$logs = $dbo->getLog();
$lastLog = end($logs['log']);
return $lastLog['query'];
}
Which is defined in appModel. I am using cakephp 2.6.9. But last query is :COMMIT which does not make any sense. I check My model convention. It is okay. Now what is the problem in my code?
Try this::
$this->PackageCustomer->id = $customer_id;
$data['PackageCustomer'] = array(
'shipment' => 2,
'comments' => $this->request->data['Ticket']['content'],
'shipment_equipment' => $this->request->data['Ticket']['shipment_equipment'],
'shipment_note' => $this->request->data['Ticket']['shipment_note'],
'issue_id' => $this->request->data['Ticket']['issue_id']
);
pr($data); exit;
$this->loadModel('PackageCustomer');
$this->PackageCustomer->save($data['PackageCustomer']);
//var_dump($this->PackageCustomer->invalidFields());
// pr($this->PackageCustomer->error);
echo $this->PackageCustomer->getLastQuery(); exit;
If the above code doesn't work I need the following answered to help further...
I need bit more information can you confirm the following:
What is the name of the table you are trying to save to?
What is the name of the class relating the to the table you are trying to save to?
Are you trying to edit or create a new record in this table?
I've read Converting Multiple Records. Now I'm trying to save multiple photos at once from a form.
With:
debug($this->request->data);
I've this:
[
(int) 1 => [
'filename' => '25483_106728809362869_5795827_n.jpg',
'description' => '',
'album_id' => '2'
],
(int) 3 => [
'filename' => '44569_193398817463220_816845208_n.jpg',
'description' => '',
'album_id' => '1'
]
]
It seems ok.
Bake has created for me this action method:
public function add() {
$photo = $this->Photos->newEntity();
if($this->request->is('post')) {
$photo = $this->Photos->patchEntity($photo, $this->request->data);
if($this->Photos->save($photo)) {
return $this->redirect(['action' => 'index']);
}
}
$this->set(compact('photo'));
}
But the CakeBook doesn't explain well how to proceed. I sense I have to use newEntities() and patchEntities(), but I don't quite understand how to do.
For example: why the newEntity() method can accept NULL, while the method newEntities() necessarily wants an argument??
The save() method accepts only one entity at a time? So, I have to cycle saving for each entity?
Can I have a small example? Thanks.
Assuming your data is in the correct format, it should be as simple as this:
$photos = $this->Photos->newEntities($this->request->data());
foreach ($photos as $photo) {
$this->Photos->save($photo);
}
newEntity() can accept a null because calling newEntity with no data creates a blank entity that you can add data to, in case you don't want to pass in request data. For example:
$photo = $this->Photos->newEntity();
$photo->description = 'Cool!';
$photo->filename = 'example.jpg';
$this->Photos->save($photo);
newEntities(), however, expects multiple data or at least an array of data if you want to make many entities.
Using saveMany:
In some occasions it would be even better using saveMany which don't need foreach loop anymore.
$entities = $this->Photos->newEntities($this->request->data());
if($this->Photos->saveMany($entities)) {
// saved
} else {
// error
}
Looking to limit the returned fields of a WP Query to help with speeding up the response from the server and reducing the amount of data retrieved. For the query I'm using, it only needs up to 3 fields of data, the rest is brought in through ACF get_field_object in the loop. Other functions I'm using such as get_posts or get_terms have field options but are limited to a small number of things, such as 'slug' only or 'id => slug'.
I'm used to developing in CakePHP, which has the option to specify each and every field to return, but the project calls for wordpress for other functionality and so I'm quite limited.
TL;DR need to speed up getting posts from Wordpress
I used fields parameter in the query and run get posts on this query.
For example: In my case, I just needed to get the Post ids for multiple categories, so I created a query like this:
$the_query = new WP_Query( array(
'ignore_sticky_posts' => 1,
'posts_per_page' => -1,
'cat' => '2,6,7' ,
'fields' => 'ids',
'post_type' => 'post',
'post_status' => 'publish',
)
);
Run the get_posts on this query:
$posts = $the_query->get_posts();
$posts will get only the IDs of particular categories posts.
Or it can also be done with the standard and popular way and i.e., by running the loop of have_posts:
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$post_id_array[] = get_the_ID();
}
}
These are the two ways to help with speeding up the response from the server and reducing the amount of data retrieved
WP_Query will return objects...so it's pretty fast. However, if you really want to limit what's returned, you can do so with the Return Fields Parameter of WP_Query.
I don't know how much it will help but below is how I'm getting a flattened array from a CPT. It's not the fastest but it could be worse. I'm using ACF to get a Custom Field but you could just get back the slug or you could get back multiple fields instead:
// Query Jobs Args
$query_args = array(
'post_type' => 'job',
'posts_per_page' => -1,
'fields' => 'ids'
);
// Get Jobs Query
$query = new WP_Query($query_args);
// Loop Persistent Vars
$job_ids = array();
// Loop Over Jobs
foreach($query->posts as $post_id) {
$job_ids[] = get_field('job_id', $post_id);
}
// Do stuff with flattened array of job ids
This is what I've done to limit the fields from WP_Query, especially, when I want to json_encode them. The $return variable contains my array of posts with only the fields listed in the $fields array.
$query = new WP_Query( array( 'post_type' => 'my_custom_type' ) );
$return = array();
$fields = array('post_title', 'ID'); //list of fields I want in $return
$posts = $query->get_posts();
foreach($posts as $post) {
$newPost = array();
foreach($fields as $field) {
$newPost[$field] = $post->$field;
}
$return[] = $newPost;
}
Interestingly enough, you can do this with the WP Rest API using the _fields parameter
https://yoursite.com/wp-json/wp/v2/posts?_fields=author,id,excerpt,title,link
More info on the API here: https://developer.wordpress.org/rest-api/
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