i have database with two values id and val so i want to ask how i can generate simple array like this
array('value', 'value2', 'value3'...);
I have
$query = $this->db->query('SELECT val FROM table');
echo $query->result_array();
But it will result something like that:
Array
(
[0] => Array
(
[val] => value
)
[1] => Array
(
[val] => value2
)
)
And i want it in one array so please if you can help me. Thanks for all answers :)
$query = $this->db->query('SELECT val FROM table')->result_array();
$array = array();
foreach ( $query as $key => $val )
{
$temp = array_values($val);
$array[] = $temp[0];
}
See it here in action: http://viper-7.com/tPd7zN
Related
I have the array as below;
I'd like to insert each name keys into tableName and get the inserted id.
For the steps, each of them will be inserted into another table tableSteps including the last inserted id of the name.
Like as below screenshot.
In my controller,
Here's what I've done so far.
$instructionsArrays = $request->instructions;
$max = count($instructionsArrays);
for ($x = 1; $x <= $max; $x++) {
foreach($instructionsArrays as $instructionsArray){
Instruction::updateOrCreate(
['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $x],
['name' => $instructionsArray['name']],
);
}
}
I was able to save sequence numbers but for names it saves only the last name key.
And... I'm really lost..
You can achieve what you want from 2 for loops
foreach($request->instructions as $key => $val){
$id = Instruction::insertGetId(
['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $key + 1],
['name' => $val['name']],
);
$data = []; //bulk insertion
$created_at = now();
foreach($val["steps"] as $step){
array_push($data, ["header_id" => $id, "name" => $step, "sequence" => $key+1, "created_at" => $created_at]); //why insert sequence when you can obtain it from the relationship?
}
Steps::insert($data);
}
With the help of the answer of #Kneegrows, I came up with the code below and it is now working. Thank you.
foreach ($request->instructions as $key => $val) {
$instruction = Instruction::updateOrCreate(
['recipe_id' => session()->get('recipeArr.id'), 'sequence' => $key + 1],
['instructions_name' => $val['name']],
);
$id = $instruction->id;
$data = []; //bulk insertion
$i = 1;
foreach ($val["steps"] as $step) {
if(!is_null($step)){
array_push($data, ["instruction_id" => $id, "steps_name" => $step, "sequence" => $i]);
$i++;
}
}
Steps::insert($data);
}
When I use this code,
$views = array();
$views[]=['somevalue'=>'customerview.php'];
$views[]=['anothervalue'=>'ordersview.php'];
I get this,
Array
(
[0] => Array
(
[somevalue] => customerview.php
)
[1] => Array
(
[anothervalue] => ordersview.php
)
)
How can I make it get rid of the initial array without using array_shift or the like? Why is it putting the numerical array in the first place instead of just this,
Array
(
[somevalue] => customerview.php
[anothervalue] => ordersview.php
)
EDIT: How can I use the short syntax for this? Is that possible?
When you do this:
$views[] = ['somevalue' => 'customerview.php'];
you're saying, "Push another element onto the array, and assign to it the following value:
'somevalue' => 'customerview.php'
But this quantity is an array key and an array value. So what you're doing is inserting into your $views array a single element that itself contains an array key and array value. This explains the behavior you're seeing.
This should give you the results you want:
$views = array();
$views['somevalue'] = 'customerview.php';
$views['anothervalue'] ='ordersview.php';
Or, in shorthand:
$views = [
'somevalue' => 'customerview.php',
'anothervalue' => 'ordersview.php'
];
or you can do:
$value1 = 'first';
$value2 = 'second';
$array = array(
$value1 => 'customerview.php',
$value2 => 'ordersview.php'
);
$views is already an array so when you use $views[], you are adding another array into the existing array.
You need to use
$views = array(
'somevalue' => 'customerview.php',
'anothervalue' => 'ordersview.php'
)
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 got a query result like this : -
Array(
[0] => Array
(
[0] => Array
(
[id] => 1
[name] => Japan
)
)
[1] => Array
(
[0] => Array
(
[id] => 2
[name] => Nepal
)
)
}
How can I convert it to
Array
(
[0] => Japan
[1] => Nepal
)
The query used to get first array is 'select id , name from country;'
Please help me.
foreach ($element as $array) {
$element = $element[0]["name"];
}
Or,
function extractName($element) {
return $element[0]["name"];
}
$newArray = array_map("extractName", $array);
Extract!
$newArray = Set::extract($oldArray, '{n}.0.name');
More here.
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