Codeigniter 4: Merge arrays then use InsertBatch to insert data in MySQL - php

I'm trying to insert multiple rows into MySQL using the 'InsertBatch' function. However, I am unable to make it work. I'm new to this, and I'm not sure if I'm doing it correctly.
I'm using input and select fields with $is data and a table with $tmp data. I used foreach and for statements to get the $tmp_data on the table. An array push() was also used to merge the data into an array.
public function Add_Fees_Matrix() {
$fm_model = new Mod_Fees_Matrix();
$data = [];
//input and select type
$is_data = [
'fm_code' => $this->request->getPost('fm_code'),
'sy_id' => $this->request->getPost('sy_id'),
'dept_id' => $this->request->getPost('dept'),
'gl_id' => $this->request->getPost('gl_id'),
'ppl_id' => $this->request->getPost('ppl_mode')
];
//table
$tmp_data = [
'fcp_description' => $_POST['fcp_description'],
'fmf_amount' => $_POST['fmf_amount']
];
foreach ($tmp_data as $k => $v) {
for($i = 0; $i < count($v);$i++) {
array_push($data, $is_data);
$data[$i][$k] = $v[$i];
}
}
echo "<pre>";
var_export($data);
$fm_model->insertBatch($data);
}
In my output, it generates four arrays. However, only the first two arrays are considered necessary. I think the problem is caused by the array push() function.
Here's the output of var_export():
array (
0 =>
array (
'fm_code' => 'FM-1741195162687292',
'sy_id' => '2',
'dept_id' => '1',
'gl_id' => '2',
'ppl_id' => '1',
'fcp_description' => 'INSTITUTIONAL DEVELOPMENT FEE',
'fmf_amount' => '123',
),
1 =>
array (
'fm_code' => 'FM-1741195162687292',
'sy_id' => '2',
'dept_id' => '1',
'gl_id' => '2',
'ppl_id' => '1',
'fcp_description' => 'MATRICULATION',
'fmf_amount' => '1230',
),
2 =>
array (
'fm_code' => 'FM-1741195162687292',
'sy_id' => '2',
'dept_id' => '1',
'gl_id' => '2',
'ppl_id' => '1',
),
3 =>
array (
'fm_code' => 'FM-1741195162687292',
'sy_id' => '2',
'dept_id' => '1',
'gl_id' => '2',
'ppl_id' => '1',
),
)
Upon clicking a button, can someone help me to insert the data on my database?

This seems to work in my problem.
public function Add_Fees_Matrix() {
$fm_model = new Mod_Fees_Matrix();
$data = [];
$tmp_data = [
'fcp_description' => $this->request->getPost('fcp_description'),
'fcp_amount' => $this->request->getPost('fmf_amount')
];
foreach ($tmp_data as $k => $v) {
for($i = 0; $i < count($v);$i++) {
$data[$i]['fm_code'] = $this->request->getPost('fm_code');
$data[$i]['sy_id'] = $this->request->getPost('sy_id');
$data[$i]['dept_id'] = $this->request->getPost('dept');
$data[$i]['gl_id'] = $this->request->getPost('gl_id');
$data[$i]['ppl_id'] = $this->request->getPost('ppl_mode');
$data[$i][$k] = $v[$i];
}
}
$fm_model->insertBatch($data);
echo "<pre>";
var_export($data);
}

Related

php array how get in array value for using foreach

I have multiple array, I want particular value get using foreach below my code
Notice: Undefined index: transId in on line 52
$test = array(
'messages' => Array
(
'resultCode' => 'Ok',
'message' => Array
(
'code' => 'I00001',
'text' => 'Successful',
),
),
'transactionResponse' => Array
(
'responseCode' => '1',
'authCode' => 'Z7K31J',
'avsResultCode' => 'Y',
'cvvResultCode' => 'P',
'cavvResultCode' => '2',
'transId' => '40004672975',
'refTransID' => Array
(
),
'transHash' => '163382584395AB06470CF365AD6F7381',
'testRequest' => '0',
'accountNumber' => 'XXXX4242',
'accountType' => 'Visa',
'messages' => Array
(
'message' => Array
(
'code' => '1',
'description' => 'This transaction has been approved',
),
),
'transHashSha2' => Array
(
),
),
);
above my array, execute $test in foreach
I want display value of transid, response, transhash
foreach ($test as $key => $value) {
$response = $value['resultCode'];
$transId = $value['transId'];
$authCode = $value['authCode'];
$transHash = $value['transHash'];
}
use array_walk_recursive() where you don't have to go in each level of the array to echo your values like below:
<?php
array_walk_recursive($test, function ($item, $key){
if($key == 'transId' || $key == 'transHash' || $key == 'resultCode'){
echo $key." => ".$item."<br>";
}
});
You dont need foreach:
$response = $test['messages']['resultCode'];
$transId = $test['transactionResponse']['transId'];
$authCode = $test['transactionResponse']['authCode'];
$transHash = $test['transactionResponse']['transHash'];
you can use this
foreach ($test as $key => $value)
{
if(!empty($value['message']))
{
$response = $value['messages']['resultCode'];
}
elseif(!empty($value['transactionResponse']))
{
$transId = $value['transactionResponse']['transId'];
$authCode = $value['transactionResponse']['authCode'];
$transHash = $value['transactionResponse']['transHash'];
}
}
if you want proper then you have to take it to array and key as your transid

Modifying multidimensional array in PHP replacing keys as the values [duplicate]

This question already has answers here:
How to swap keys with values in array?
(6 answers)
Closed 6 years ago.
How would you modify the following code using only a foreach loop by replacing the keys as the values? For examples the salad, chicken, and pancakes keys would the values instead.
$meals = array(
'Lunch' => array(
'salad' => 'italian',
'salad2' => 'ranch',
'salad3' => 'sesame',
'salad4' => 'bluecheese'
),
'Dinner' => array(
'chicken' => 'grilled',
'chicken2' => 'baked',
'chicken3' => 'steamed',
'chicken4' => 'fried',
'chicken5' => 'broiled'
),
'Breakfast' => array(
'pancakes' => 'blueberry',
'pancakes2' => 'cherry',
'pancakes3' => 'strawberry',
'pancakes4' => 'lemon'
)
);
$newkey = array();
foreach($meals as $key => $value) {
unset($value);
// foreach ($)...
}
print_r($meals);
Edit
If you're unable to use array_flip(), then you'll need to do two loops: one for each meal, and one for each meal option.
Example:
foreach ($meals as $meal => $mealOptions)
{
$revisedMealOptions = array();
foreach ($mealOptions as $originalKey => $newKey)
{
$revisedMealOptions[$newKey] = $originalKey;
}
$meals[$meal] = $revisedMealOptions;
}
Original Answer
It's not entirely clear what you're after. If all you want is to turn:
'Lunch' => array(
'salad' => 'italian'
);
into
'Lunch' => array(
'italian' => 'salad'
);
use array_flip().
Example:
$meals['Lunch'] = array_flip($meals['Lunch']);
See http://php.net/manual/en/function.array-flip.php.
I'm sorry I am a total beginner. I need to use a nested $foreach loop to address this question. For class I'm not allowed to use the array_flip function. I have tried
$newkey = array();
foreach($meals as $key => $value) {
$newkey[] = $value;
foreach ($value as ){
}
}
So, it would read:
Basically I need it to read:
Array(
[Lunch] => array(
[italian] => salad,
[ranch] => salad2,
[sesame] => salad3,
[bluecheese] => salad4
)
)
The easiest way to do it would be like this:
$meals = array(
'Lunch' => array(
'salad' => 'italian',
'salad2' => 'ranch',
'salad3' => 'sesame',
'salad4' => 'bluecheese'
),
'Dinner' => array(
'chicken' => 'grilled',
'chicken2' => 'baked',
'chicken3' => 'steamed',
'chicken4' => 'fried',
'chicken5' => 'broiled'
),
'Breakfast' => array(
'pancakes' => 'blueberry',
'pancakes2' => 'cherry',
'pancakes3' => 'strawberry',
'pancakes4' => 'lemon'
)
);
$newArray = array();
foreach ($meals as $key => $value) {
$temp = array();
foreach ($value as $innerKey => $innerValue) {
$temp[$innerValue] = $innerKey;
}
$newArray[$key] = $temp;
}
unset($meals);
Basically, you create a new array and build it from the beginning with the use of the array $meals.

unable to delete array key from multidimensional array in cakephp

I want to delete array index which contain rating 0 here is my array
array(
(int) 0 => array(
'Gig' => array(
'id' => '1',
'rating' => (int) 5
)
),
(int) 1 => array(
'Gig' => array(
'id' => '3',
'rating' => (int) 9
)
),
(int) 2 => array(
'Gig' => array(
'id' => '4',
'rating' => '0'
)
)
)
and what I did
for($i = 0; $i<count($agetGigsItem); $i++)
{
if($agetGigsItem[$i]['Gig']['rating']==0)
{
unset($agetGigsItem[$i]);
}
$this->set('agetGigsItem', $agetGigsItem);
}
i also try foreach loop but unable to resolve this issue.
foreach ($agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] == 0) { unset($agetGigsItem[$key]); }
}
I think you need to reupdate your array.
foreach ($agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] != 0)
{
unset($agetGigsItem[$key]);
}
$this->set('agetGigsItem', $agetGigsItem);
}
I hope you are missing $this and so you cannot access the array in CakePHP.
So try this:
foreach ($this->$agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] == 0) {
unset($this->$agetGigsItem[$key]);
}
}
This code will unset arrey index with value 0.
<?php
$array=array(
array(
'Gig' => array(
'id' => '1',
'rating' =>5
)
),
array(
'Gig' => array(
'id' => '3',
'rating' =>9
)
),
array(
'Gig' => array(
'id' => '4',
'rating' =>0
)
)
);
foreach($array as $a){
if($a['Gig']['rating']==0){
unset($a['Gig']['rating']);
}
$array1[]=$a;
}
var_dump($array1);
Destroying occurances within an array you are actually processing over with a for or a foreach is always a bad idea. Each time you destroy an occurance the loop can easily get corrupted and get in a terrible mess.
If you want to remove items from an array it is better to create a copy of the array and process over that new array in the loop but remove the items from the original array.
So try this instead
$tmparray = $this->agetGigsItem; // will copy agetGigsItem into new array
foreach ($tmparray as $key => $value) {
if ($value["Gig"]["rating"] == 0) {
unset($this->agetGigsItem[$key]);
}
}
unset($tmparray);

Convert a 2D array to JSON in PHP

My goal is to make a single database hit to generate a JSON array of objects with attributes that could be also be an array of objects, which could also have attributes that array of objects etc of an arbitrary (but known) depth.
I get a 2D array from my database using a PDO object.
$stmt = $this->pdo->prepare($sql);
$stmt->execute($args);
$TwoDimArray = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $TwoDimArray;
So in my example, I have a Quiz, that can have questions, that can have answers. So a depth of 3. So assuming I have a 2D Array such as the table below, how would I make this JSON array using that data. (Note: other data has been removed for clarity sake, but questions and answers could have other attributes.)
Edit: This is my attempt. It is horribly inefficient and not very abstract for the general case but this code will achieve the right answer for small data sets.
$data = ($database -> query($sql,$args)); // the result is $TwoDimArray
$quizes = array();
$quiz_id_list = array();
foreach($data as $quizkey => $quizvalue){
if(!in_array($quizvalue["quiz_id"], $quiz_id_list)) {
array_push($quiz_id_list, $quizvalue["quiz_id"]);
$question_id_list = array();
$questions = array();
foreach ($data as $questionskey => $questionsvalue) {
if ($quizvalue["quiz_id"] == $questionsvalue["quiz_id"] && !in_array($questionsvalue["question_id"], $question_id_list)) {
$answers = array();
array_push($question_id_list, $questionsvalue["question_id"]);
foreach ($data as $answerskey => $answersvalue) {
$myanswer = array();
if ($questionsvalue["question_id"] == $answersvalue["question_id"]) {
$myanswer["answer_id"] = $answersvalue["answer_id"];
array_push($answers, $myanswer);
}
}
$myquestion = array();
$myquestion["question_id"] = $questionsvalue["question_id"];
$myquestion["answers"] = $answers;
array_push($questions, $myquestion);
}
}
$myquiz = array();
$myquiz["quiz_id"] = $quizvalue["quiz_id"];
$myquiz["questions"] = $questions;
array_push($quizes, $myquiz);
}
}
return json_encode($quizes);
The contents of $data looks like this:
array (
0 =>array('quiz_id' => '1', 'question_id' => '1', 'answer_id' => '1',),
1 =>array('quiz_id' => '1', 'question_id' => '1', 'answer_id' => '2',),
...
5 =>array('quiz_id' => '1', 'question_id' => '2', 'answer_id' => '6',),
6 =>array('quiz_id' => '1', 'question_id' => '2', 'answer_id' => '7',),
...
22 =>array('quiz_id' => '2', 'question_id' => '6', 'answer_id' => '23',),
23 =>array('quiz_id' => '2', 'question_id' => '6', 'answer_id' => '24',),
)
The result should return a json object that looks like this:
[
{
"quiz_id": 1,
"questions": [
{"question_id":1, "answers": [{"answer_id":1}, {"answer_id":2}, {"answer_id":3},{"answer_id":4}]},
{"question_id":2, "answers": [{"answer_id":5}, {"answer_id":6}, {"answer_id":7},{"answer_id":8}]},
{"question_id":3, "answers": [{"answer_id":9}, {"answer_id":10}, {"answer_id":11},{"answer_id":12}]}
]
},
{
"quiz_id": 2,
"questions": [
{"question_id":4, "answers": [{"answer_id":13}, {"answer_id":14}, {"answer_id":15},{"answer_id":16}]},
{"question_id":5, "answers": [{"answer_id":17}, {"answer_id":18}, {"answer_id":19},{"answer_id":20}]},
{"question_id":6, "answers": [{"answer_id":21}, {"answer_id":22}, {"answer_id":23},{"answer_id":24}]}
]
}
]
You say this is the contents of $TwoDimArray There is not much that can be done with it. I suspect there is something missing yet.
array ( 'quiz_id' => '1', 'question_id' => '1', 'answer_id' => '1', ),
array ( 'quiz_id' => '1', 'question_id' => '1', 'answer_id' => '2', ),
array ( 'quiz_id' => '1', 'question_id' => '1', 'answer_id' => '3', ),
This will get rid of your "redundant data":
foreach($TwoDimArray as $value){
$quiz[$value['quiz_id']][$value['question_id']][$value['question_id']] = 1;
}

how to find a element in a nested array and get its sub array index

when searching an element in a nested array, could i get back it's 1st level nesting index.
<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k, $search_query){
global $cnt;
if($v == $search_query){
/* i want the sub array index to be returned */
}
}
?>
i.e to say, if i'am searching 'victor', i would like to have 'dep1' as the return value.
Could anyone help ??
Try:
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($coll), RecursiveIteratorIterator::SELF_FIRST);
/* These will be used to keep a record of the
current parent element it's accessing the childs of */
$parent_index = 0;
$parent = '';
$parent_keys = array_keys($coll); //getting the first level keys like dep1,dep2
$size = sizeof($parent_keys);
$flag=0; //to check if value has been found
foreach ($iter as $k=>$val) {
//if dep1 matches, record it until it shifts to dep2
if($k === $parent_keys[$parent_index]){
$parent = $k;
//making sure the counter is not incremented
//more than the number of elements present
($parent_index<$size-1)?$parent_index++:'';
}
if ($val == $name) {
//if the value is found, set flag and break the loop
$flag = 1;
break;
}
}
($flag==0)?$parent='':''; //this means the search string could not be found
echo 'Key = '.$parent;
Demo
This works , but I don't know if you are ok with this...
<?php
$name = 'linda';
$col1=array ( 'dep1' => array ( 'fy' => array ( 0 => 'john', 1 => 'johnny', 2 => 'victor', ), 'sy' => array ( 0 => 'david', 1 => 'arthur', ), 'ty' => array ( 0 => 'sam', 1 => 'joe', 2 => 'victor', ), ), 'dep2' => array ( 'fy' => array ( 0 => 'natalie', 1 => 'linda', 2 => 'molly', ), 'sy' => array ( 0 => 'katie', 1 => 'helen', 2 => 'sam', 3 => 'ravi', 4 => 'vipul', ), 'ty' => array ( 0 => 'sharon', 1 => 'julia', 2 => 'maddy', ), ), );
foreach($col2 as $k=>$arr)
{
foreach($arr as $k1=>$arr2)
{
if(in_array($name,$arr2))
{
echo $k;
break;
}
}
}
OUTPUT :
dept2
Demo

Categories