Adding elements to array? - laravel

How can I add more than one element to my keyed array?
array_add($myArray, 'key', 'a');
array_add($myArray, 'key-2', 'b');
Is there a better way?

There is no need for any other custom function because in PHP there is a built-in function for this and it's array_merge and you can use it like this:
$myArray = array('one' => 'TheOne', 'two' => 'TheTwo');
$array = array_merge($myArray, array('three' => 'TheThree', 'four' => 'TheFour'));
print_r($array);
Output:
Array
(
[one] => TheOne
[two] => TheTwo
[three] => TheThree
[four] => TheFour
)
You can also use this:
$myArray1 = array('one' => 'TheOne', 'two' => 'TheTwo');
$myArray2 = array('three' => 'TheThree', 'four' => 'TheFour');;
$array = $myArray1 + $myArray2;
print_r($array);
Output:
Array
(
[one] => TheOne
[two] => TheTwo
[three] => TheThree
[four] => TheFour
)

I prefer:
$myArray['key'] = 'a';
$myArray['key-2'] = 'b';
But this is not really better, because you're not adding more than one in a single command.
And if you really need to add multiple, you can always create a helper:
function array_add_multiple($array, $items)
{
foreach($items as $key => $value)
{
$array = array_add($items, $key, $value);
}
return $array;
}
And use it as
$array = array_add_multiple($array, ['key' => 'a', 'key-2' => 'b']);
or, if you're not using PHP 5.4:
$array = array_add_multiple($array, array('key' => 'a', 'key-2' => 'b'));

My custom "on the fly" method:
function add_to_array($key_value)
{
$arr = [];
foreach ($key_value as $key => $value) {
$arr[] = [$key=>$value];
}
return $arr;
}
dd(add_to_array(["hello"=>"from this array","and"=>"one more time","what"=>"do you think?"]));

Related

Laravel : array_push not working in collection->each() iterator

I have grouped collection and I iterate it using each() function.Inside the each function I want to add element to some array.But it is not working.Any idea?
$dataSet1 = [];
$appointments = [
['department' => 'finance', 'product' => 'Chair'],
['department' => 'marketing', 'product' => 'Bookcase'],
['department' => 'finance', 'product' => 'Desk'],
];
$groupData = collect($appointments)->groupBy('department');
$groupData->each(function ($item, $key) {
Log::info($key); //Show correct output in log
array_push($dataSet1, $key); //ERROR
array_push($dataSet1, 'A');//ERROR
});
Laravel version : 8.35.1
You need to pass the array to the function with use:
$groupData->each(function ($item, $key) use (&$dataSet1) {
Log::info($key); //Show correct output in log
array_push($dataSet1, $key); //ERROR
array_push($dataSet1, 'A');//ERROR
});
Pass-by-reference (&) is needed as long as $dataSet1 is not an object instance.

How to add months dynamically which is stored in database as a header in excel file while exporting using laravel?

Suppose I have items in database which is stored from an Excel file. All the items should be below the header of the months. I have also stored months from the file in the database. So, I want those months to be the header of those items and it's related records. In simple words, I want the header to be dynamic. This is what I have done.
I have tried many code scripts but nothing works. Like Laravel, Excel etc. Can anyone suggest me a good approach?
public function test(){
$data = Item::where('category_id',7)->get()->toArray();
$data2 = month::all();
$itemsArray[] = ['Category Id','Item Name','Created At','Updated At'];
foreach ($data as $value) {
// dd($value);
$itemsArray[] = array(
'Category Id' => $value['category_id'],
'Item Name' => $value['name'],
'Created At' => $value['created_at'],
'Updated At' => $value['updated_at'],
);
}
// Generate and return the spreadsheet
Excel::create('Items', function($excel) use ($itemsArray) {
// Set the spreadsheet title, creator, and description
$excel->setTitle('Items');
// Build the spreadsheet, passing in the items array
$excel->sheet('Items', function($sheet) use ($itemsArray) {
$cellRange = 'A1:D1';
// $spreadsheet->getActiveSheet()->getStyle('A1:D4')
// ->getAlignment()->setWrapText(true);
$sheet->getStyle($cellRange)->getFont()->setBold( true );
$sheet->getStyle($cellRange)->getFont()->setSize( '15' );
$sheet->setBorder($cellRange, 'thick' );
$sheet->getStyle($cellRange)->applyFromArray(array(
'fill' => array(
// 'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'A5D9FF')
)
));
$sheet->fromArray($itemsArray, null, 'A1', false, false);
});
$excel->setCreator('Laravel')->setCompany('Dev505');
$excel->setDescription('Items file');
})->download('xlsx');
}
I need help for getting the actual result.
Akhtar i suggest use to kindly install the Carbon package
https://carbon.nesbot.com/docs/
Try by updating the below code.
$data = Item::where('category_id',7)->get(); // removed toArray()
$data2 = month::all();
$itemsArray[] = ['Category Id','Item Name','Created At','Updated At'];
foreach ($data as $key=>$value) {
$itemsArray[] = array(
'month' => Carbon::now()->addMonth($key)->format('m-Y');
'Category Id' => $value['category_id'],
'Item Name' => $value['name'],
'Created At' => $value['created_at'],
'Updated At' => $value['updated_at'],
);
}
This is the actual code which I have used for excel file. I have solved my problem. Thanks and yeah I am posting this code, if anyone can get help from it.
public function export(){
$data = Category::all();
foreach ($data as $value) {
$value['items'] = Item::where('category_id',$value['id'])->get();
foreach ($value['items'] as $vl) {
$vl['record'] = Record::where('item_id',$vl['id'])->get();
}
}
$data2 = month::pluck('id','month');
foreach ($data2 as $key => $value) {
$m[] = $key;
}
array_unshift($m, 'Categories'); //Insert new element at the start of array
array_push($m, 'Total');
$itemsArray[] = $m;
foreach ($data as $value) {
$itemsArray[] = array(
$itemsArray[0][0] => $value['name'],
// $itemsArray[0][13] => 'Total',
);
foreach ($value['items'] as $val) {
$records_array = [];
$i = 0;
foreach ($val['record'] as $val5) {
$recordval = $val5['value'];
$records_array[$i] = $val5['value'];
$i++;
}
$itemsArray[] = array(
$itemsArray[0][0] => $val['name'],
$itemsArray[0][1] => $records_array[0],
$itemsArray[0][2] => $records_array[1],
$itemsArray[0][3] => $records_array[2],
$itemsArray[0][4] => $records_array[3],
$itemsArray[0][5] => $records_array[4],
$itemsArray[0][6] => $records_array[5],
$itemsArray[0][7] => $records_array[6],
$itemsArray[0][8] => $records_array[7],
$itemsArray[0][9] => $records_array[8],
$itemsArray[0][10] => $records_array[9],
$itemsArray[0][11] => $records_array[10],
$itemsArray[0][12] => $records_array[11],
// $itemsArray[0][13] => 'Total',
);
}
}
// Generate and return the spreadsheet
Excel::create('Items', function($excel) use ($itemsArray) {
// Set the spreadsheet title, creator, and description
$excel->setTitle('Items');
// Build the spreadsheet, passing in the items array
$excel->sheet('Items', function($sheet) use ($itemsArray) {
$cellRange = 'A1:M1';
$sheet->getStyle($cellRange)->getFont()->setBold( true );
$sheet->getStyle($cellRange)->getFont()->setSize( '12' );
$sheet->setBorder($cellRange, 'thin' );
$sheet->getStyle($cellRange)->applyFromArray(array(
'fill' => array(
// 'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'A5D9FF')
)
));
$sheet->fromArray($itemsArray, null, 'A1', false, false);
});
$excel->setCreator('Laravel')->setCompany('Dev505');
$excel->setDescription('Items file');
})->download('xlsx');
}

Codeigniter update_batch--view, but not execute

I am using Codeigniter 3.x and want to see an update_batch query, but not run it, while I am debugging the code.
This works for an update_batch:
$this->db->update_batch("`" . $this->fullGamesTable . "`", $fullGames, 'gameid');
and updates the database, but I want to view the update and not actually do the update.
Thanks.
Can you do like this
$data = array(
array(
'opt_id' => $hoptid1,
'q_id' => $hid,
'opt_val' => $sin_yes,
'opt_crct' => $sin_yescrt,
'opt_mark' => '1'
),
array(
'opt_id' => $hoptid2,
'q_id' => $hid,
'opt_val' => $sin_no,
'opt_crct' => $sin_nocrt,
'opt_mark' => '1'
)
);
$this->db->update_batch('option', $data, 'opt_id');
Try this
public function update_batch()
{
$data = $this->db->select('id,description')->from('insert_batch')->group_by('url')->get()->result_array();
$batch_update = [];
foreach ($data as $key => $value) {
$value['description'] = 'description';
$batch_update[] = [
'id' =>$value['id'],
'description' => $value['description']
];
}
echo "<pre>"; print_r($batch_update);
$this->db->update_batch('insert_batch',$batch_update,'id');
}

The reason why Cannot access empty property ?

I'm new to this...help me please
$data is object
stdClass Object ( [menu_id] => 38 [menu_code] => M062 [menu_name] => BAP (RICE) [price] => Rp 6.364 [total] => 1
and $fields is array, this is not all..
Array ( [0] => Array ( [code] => menu_id [title] => ID [width] => 5 ) [1] => Array ( [code] => menu_code [title] => Kode [width] => 8 ) [2] =>
and this is my function :
function writeRowAsli($row, $startChar, $fields, $data){
$i=$startChar; $j=''; $k='';
foreach($fields as $field){
$k = $j.$i;
$this->excel->getActiveSheet()->setCellValue($k.$row, $data->$field['code']);
$last = $k;
if($i == 'Z'){
$i='A';
$j.=$i;
} else $i++;
}
$this->excel->getActiveSheet()->setCellValue($j.$i.$row, '=SUM(C'.$row.':'.$k.$row.')');
}
i know the bad line is $this->excel->getActiveSheet()->setCellValue($k.$row, $data->$field['code']);
thanks all
Change your function as below and check if its work or not:
function writeRowAsli($row, $startChar, $fields, $data){
$i=$startChar; $j=''; $k='';
$fields = array_filter($fields);
foreach($fields as $field){
$k = $j.$i;
$this->excel->getActiveSheet()->setCellValue($k.$row, $data->$field['code']);
$last = $k;
if($i == 'Z'){
$i='A';
$j.=$i;
} else $i++;
}
$this->excel->getActiveSheet()->setCellValue($j.$i.$row, '=SUM(C'.$row.':'.$k.$row.')');
}

convert select DB::table to array on laravel

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

Resources