Let's say you have following data:
$array = ['23' => 'item', '32' => 'another item', '1' => 'More items'];
Using
return response()->json($array);
Will decode data element following:
{
1 : 'More Items'
23 : 'Item'
32 : 'Another Item'
}
To prevent array resorting put it into object's variable as such:
$array = ['23' => 'item', '32' => 'another item', '1' => 'More items'];
$returnData = ['unsorted' => $array];
return response()->json($returnData);
This becomes a problem for orderBy() queries. You can alternatively, add orderBy()->values();
Related
How would one do the following elegantly with laravel collections ?
Map the values of the $baseMap as keys to the collection.
The baseMap :
$baseMap = [
'name' => 'new_name',
'year' => 'new_year',
];
The collection :
$items = collect([
[
'name' => 'name1',
'year' => '1000',
'not_in_basemap' => 'foo'
],
[
'name' => 'name2',
'year' => '2000',
'not_in_basemap' => 'foo'
],
//...
]);
The end result :
$result =[
[
'new_name' => 'name1',
'new_year' => '1000',
],
[
'new_name'=> 'name2',
'new_year' => '2000',
],
];
I know how to do it in plain php , just wondering what a nice collection version would be. Thanks!
I tried to find collection methods, or php functions, but without success. Some dirty code that works with different keys from both sides (items and basemap).
$result = $items->map(function($item) use ($baseMap) {
$array = [];
foreach($baseMap as $oldKey => $newKey){
if(isset($item[$oldKey])){
$array[$newKey] = $item[$oldKey];
}
}
return $array;
});
$result = $result->toArray();
Thanks to #vivek_23 and #IndianCoding for giving me idea's I ended up with the following :
I made a small edit to make sure the mapping and the items keys lined up.
so you don't have to worry of misalignment and all in laravel collection !
$baseMap = collect($baseMap)->sortKeys();
$result = $items->map(function ($item) use ($baseMap) {
return $baseMap->values()
->combine(
collect($item)->sortKeys()->intersectByKeys($baseMap)
)
->all();
});
Use intersectByKeys to filter your baseMap keys with $items values.
$result = $items->map(function($item,$key) use ($baseMap){
return array_combine(array_values($baseMap),collect($item)->intersectByKeys($baseMap)->all());
});
dd($result);
Update:
In a pure collection way,
$baseMapCollect = collect($baseMap);
$result = $items->map(function($item,$key) use ($baseMapCollect){
return $baseMapCollect->values()->combine(collect($item)->intersectByKeys($baseMapCollect->all())->values())->all();
});
dd($result);
Here are my two cents, using map. Don't know how dynamic your collection should be, but knowing the keys I would do the following:
$baseMap = [
'name' => 'new_name',
'year' => 'new_year',
];
$items = collect([
[
'name' => 'name1',
'year' => '1000',
'not_in_basemap' => 'foo'
],
[
'name' => 'name2',
'year' => '2000',
'not_in_basemap' => 'foo'
],
])->map(function($item, $key) use ($baseMap) {
return [
$baseMap['name'] => $item['name'],
$baseMap['year'] => $item['year']
];
});
i want to change this code
$data = array(
'O' => 'Orange',
'Y' => 'Yellow',
'G' => 'Green',
'B' => 'Blue',
'I' => 'Indigo',
'V' => 'Violet',
);
with this code
$d = DB::table('sps')
->select(array('sps.namasp'))
->where('namasp','like',$term)
->get();
Here is my full code on route
Route::get('getdata', function()
{
$term = Input::get('term');
$data = array(
'SPION DEPAN' => 'Spion Depan',
'SPION TENGAH' => 'Spion Tengah',
'O' => 'Orange',
'Y' => 'Yellow',
'G' => 'Green',
'B' => 'Blue',
'I' => 'Indigo',
'V' => 'Violet',
);
$return_array = array();
foreach ($data as $k => $v) {
if (strpos($v, $term) !== FALSE) {
$return_array[] = array('value' => $v, 'id' =>$k);
}
}
return Response::json($return_array);
});
basicly i try to find code for autocomplete on my blade. and i stack here.
if you have any references for search autocomplete on laravel 5.1, give me the example or link. thanks before :)
You can get array using lists method
$d = DB::table('sps')
->select(array('sps.namasp'))
->where('namasp','like',$term)
->lists("<< value >>","<< key >>");
This query is return an array.
Note:-
<< value >> replace to your table field that make value of array.
<< key >> replace to your table filed that make key of array
I wrote this two line in a phtml page:
$array = Mage::getStoreConfig('extcontacts/extendedcontactsGroup');
var_dump($array);
And this is the result:
array (size=8)
'excontactus_select' => string '1' (length=1)
'defaultrecipient_text' => string 'soufiane.marar1#gmail.com' (length=25)
'departements_textarea' => string 'Sales Department,sales#example.com
Support Department,support#example.com' (length=74)
'staticblock_select' => string '1' (length=1)
'contactfrm_select' => string '0' (length=1)
'emailsender_select' => string 'general' (length=7)
'sendcopytosender_select' => string '0' (length=1)
'emailtemplate_select' => string 'extcontacts_extendedcontacts_group_emailtemplate_select' (length=55)
For select it returns 1 or 0 and I don't want 1 or 0 to be returned I want the string.
staticblock_select items example = block1,block2,block3...
How can I do to make it return the selected value?
Well, you need to create your own, Store Config Dropdown class for that select element.
I recommend to read this, there is a detailed description how to do it:
Link to Custom Store Config settings
Especially check this part:
<?php
class JR_CustomConfigExample_Model_System_Config_Source_Dropdown_Values
{
public function toOptionArray()
{
return array(
array(
'value' => 'key1',
'label' => 'Value 1',
),
array(
'value' => 'key2',
'label' => 'Value 2',
),
);
}
}
Don't forget to change you system.xml also this part:
<source_model>adminhtml/system_config_source_yesno</source_model>
Without to seeing your full module files, I could help with this one. Hope it helped, to point to the right direction.
i found the solution and this is it :
public function toOptionArray()
{
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('core_read');
$query = 'SELECT title FROM ' . $resource->getTableName('cms/block');
$results = $readConnection->fetchAll($query);
$monarray = array();
$compt = 1;
foreach ($results as $key => $value) {
foreach ($value as $key2 => $value2) {
the solution ==> $monarray[$compt-1] = array('value'=>$value2,
'label'=>Mage::helper('extendedcontacts')->__($value2));
$compt++;
}
}
return $monarray;
}
i changed this line :
$monarray[$compt-1] = array('value'=>$compt,'label'=>Mage::helper('extendedcontacts')->__($value2));
to this line :
$monarray[$compt-1] = array('value'=>$value2,'label'=>Mage::helper('extendedcontacts')->__($value2));
and thas the result it returns footer links as example :
array (size=8)
'excontactusSelect' => string '1' (length=1)
'staticblockSelect' => string 'Footer Links' (length=12)
'contactfrmSelect' => string '1' (length=1)
'defaultrecipientText' => string 'soufiane.marar1#gmail.com' (length=25)
'emailsenderSelect' => string 'general' (length=7)
'sendcopytosenderSelect' => string '0' (length=1)
'emailtemplateSelect' => string 'extcontacts_extendedcontactsGroup_emailtemplateSelect' (length=53)
'departementsTextarea' => string '' (length=0)
this is the module conf :
http://i.stack.imgur.com/tlBfa.png
I have been looking around but I have not found an answer yet. Kindly help if you know the answer.
How do you update multiple rows in CI?
In my MySQL:
I have column names:
ID, Settings Name, Settings Value ( Settings Name is Unique )
I have the ff Data:
ID = 1, Settings Name = "Hello" , Settings Value = "True"
ID = 2, Settings Name = "World", Settings Value = "Good"
and more ...
I also have a form that gets the Settings Value but I am not sure how to update it on the DB. How to update the True for the Hello being the Settings Name and update the Good for the World.
I heard about insert_batch() but is there an update_batch()?
Are you using Active record?
Yes there is an update batch: $this->db->update_batch();
$data = array(
array(
'ID' => 1 ,
'Settings Name' => 'Hello' ,
'Settings Value' => 'True'
),
array(
'ID' => '2' ,
'Settings Name' => 'World' ,
'Settings Value' => 'Good'
)
);
$this->db->update_batch('mytable', $data, 'where_key');
From the documentation:
The first parameter will contain the table name, the second is an associative array of values, the third parameter is the where key.
There is indeed an update_batch() method available in CodeIgniter already.
You can use it your example like so:
$data = array(
array(
'ID' => 1,
'Settings Name' => 'Hello',
'Settings Value' => 'True'
),
array(
'ID' => 2,
'Settings Name' => 'World',
'Settings Value' => 'Good'
)
);
$this->db->update_batch('tableName', $data, 'id');
So what you have is an array of arrays, the children basically hold the data for each row in the database. The first parameter for update_batch() is the name of the database table, the second is the $data variable and the third is the column you want to use in the WHEN clause.
Here is a simple php code for perform this operations.
<?php
function basic_update($uwi='') {
$this->load->database();
$data = array(
'ID' => 1,
'Settings Name' => 'Hello',
'Settings Value' => 'True'
);
$this->db->where('ID', '1');
$this->db->update('<table name>', $data);
$data1 = array(
'ID' => 2,
'Settings Name' => 'World',
'Settings Value' => 'Good'
);
$this->db->where('ID', '2');
$this->db->update('<table name>', $data1);
}
In $this->db->where('ID', '1'); ID is your table field and 1 is the value.
In array first parameter will contain the table name, the second parameter is an associative array of values
I use the ion auth for codeigniter and it works great except that I don't know how to code drop down list the same way as the text field.
If you want to display a text field under view you have to issue this:
<?php echo form_input($first_name);?>
And this is the code under controller:
$this->data['first_name'] = array(
'name' => 'first_name',
'id' => 'first_name',
'type' => 'text',
'size' => 32,
'maxlength' => 32,
'value' => $this->form_validation->set_value('first_name'),
);
But how can I put the value of my drop down list into an array?
I tried putting this code under view:
<?php
$options = array(
'' => 'Select',
'Dr' => 'Dr.',
'Mr' => 'Mr.',
'Mrs' => 'Mrs.',
'Ms' => 'Ms.',
'Prof' => 'Prof.',
'Mr. & Mrs.' => 'Mr. & Mrs.',
);
echo form_dropdown('title', $options, '$title');
?>
I am thinking that under view I should code it like: echo form_dropdown($title); the same as text field but what is the code under controller?
First in your controller you can do :
$options = array(
'0' => 'Select',
'Dr' => 'Dr.',
'Mr' => 'Mr.',
'Mrs' => 'Mrs.',
'Ms' => 'Ms.',
'Prof' => 'Prof.',
'Mr. & Mrs.' => 'Mr. & Mrs.',
);
$data['options'] = $options
$this->load->view('your_view',$data);
In the View :
echo form_dropdown('title', $options, set_value('title'));
Moreover think you want to retain the value of the dropdown if a form validation error occurs:
you just need to put some validation to retain the values of the dropdown , somethin like:
$this->form_validation->set_rules('title','Titles','alpha');
If not validatted the dropdown will not retain the values in spite of using set_value