How to insert_batch() in Codeigniter 3 with "inconsistent?" array associative - php

I've Googling but the results doesn't match with my problem.
so, i have this array:
$data1 = array(
'DRAWING_NO'=>123,
'NO_PLANNING'=>321,
);
$data2 = array(
'DRAWING_NO'=>456,
'NO_PLANNING'=>654,
'ON_CREATE'=>date('Y-m-d H:i:s')
);
then i'm doing insert_batch()
$this->db->insert_batch('tb_drawing_lvl',array($data1,$data2));
but i got error
yes, i knew it, because in $data1 i don't give 'ON_CREATE' key. but i want insert them to my table and the result is like this
How to do that using insert_batch?

I ended up applying the below logic.
Actually What I did is created a separate array and and went through the loop of the existing array and checked if the necessary key and values exists, if not i have added those keys and performed batch insert with the all the keys required!
$data = array(
array(
'DRAWING_NO' => 121 ,
'NO_PLANNING' => 123
),
array(
'DRAWING_NO'=>456,
'NO_PLANNING'=>654,
'ON_CREATE'=>date('Y-m-d H:i:s')
)
);
$row_arr = array();
foreach($data as $row){
$temp = array(
'DRAWING_NO' => isset($row['DRAWING_NO']) ? $row['DRAWING_NO'] : NULL,
'NO_PLANNING' => isset($row['NO_PLANNING']) ? $row['NO_PLANNING'] : NULL,
'ON_CREATE' => isset($row['ON_CREATE']) ? $row['ON_CREATE'] : date('Y-m-d H:i:s')
);
array_push($row_arr,$temp);
}
$this->db->insert_batch('test',$row_arr);

Related

Php, remove key from an array red-handed

I want to remove an item from an array. I can write this:
$item = array(
'id' => 1
'name' => 'name'
);
$item2 = $item;
unset($item2['id']);
$names[] = $item2;
but the last 3 lines are somewhat "cumbersome", soo un elegant. Can it be solved without creating $item2 ? Something like:
$item = array(
'id' => 1
'name' => 'name'
);
$names[] = array_ignore_index('id', $item);
From your codes, I can see that you are trying to get the names[] from item array. One possible simple solution for this specific scenario:
For example IF you have :
$items = array(
array(
//this is your item 1
'id' => 1,
'name' => 'name1'
),
array(
//this is item 2
'id' => 2,
'name' => 'name2'
)
);
and you want to retrieve the names in the names array.
You can just do:
$names = array_column($items, 'name');
It will return:
Array
(
[0] => "name1"
[1] => "name2"
)
Please note this solution is best fit for this specific scenario, it may not fit your current scenario depending.
The shortest out of the box solution is to create a diff of the array keys:
$names[] = array_diff_key($item, array_flip(['id']));
See http://php.net/array_diff_key.
function array_ignore_index($id,$item){ ///function
unset($item[$id]);
return $item;
}
$a=array('id'=>1,
'name'=>'name');
$b=array_ignore_index('name',$a);
echo $b['name']; //create error id is not present
Here is the code for required operation..
You can use unset array column
Code is
unset($item['id']);
To test it
print_r($item);

How to auto-generate array key values if they are null (from a query)

My application uses many arrays, and many sql queries. My issue is within this code:
I execute this query:
$select = "SELECT name, surname FROM table"
$query = $connection->query($select);
$array = $query->fetchAll(PDO::FETCH_ASSOC);
Then, I pass the values into an array like this:
$array_dump= array(
array(
array('name' => 'name'),
array('content' => $array['name'])
),
array(
array('name' => 'surname'),
array('content' => $array['surname'])
),
)
In fact, this works properly, if you don't set error_reporting(). If I turn on, I get this error:
Notice: Undefined index: surname in C:\AppServ\www\test.php on line 27
This actually happens, due the array was not set. In other words, surname value is empty.
My trouble:
I must use this methodology, but I can't use something like this (got error):
array(
array('name' => 'name'),
array('content' => (isset($array['surname']) ? $array['surname'] : '')
)
My question
As you see, this ain't an error properly, but that "Notice" should not appear (as INDEX is not defined...). Is there any way to set ALL array keys by default, from that query, even if the values are NULL, such as "surname" field? That would be the fastest solution. I've been looking for this, but got no answer.
Thanks!
You should be iterating over the results and formatting them as necessary. Something like this:
$array = $query->fetchAll(PDO::FETCH_ASSOC);
$array_dump = array();
foreach ( $array as $person ) {
$tempArray = array();
array_push($tempArray, array(
'name' => 'name',
'content' => $person['name']
));
array_push($tempArray, array(
'name' => 'surname',
'content' => $person['surname']
));
array_push($array_dump, $tempArray);
}
There is no way to set ALL possible array keys by default. But you can build array of default values based on predefined set of keys and merge it with main array. Somehow like this:
$a_keys = array('name', 'surname');
$a_defaults = array_combine($a_keys, array_fill(0, count($a_keys), 0));
$array = array_merge($a_defaults, $array);
...

Passing an Associative array into another associative array in PHP

apologies if this is a simple fix - I'm having trouble passing a few arrays in PHP.
I have two arrays setup eg:
$person = array(
'height' => 100,
'build' => "average",
'waist' => 38,
);
$hobbies = array(
'climbing' => true,
'skiing' => false,
'waist' => 38,
);
now if I perform a print_r() on these arrays they return results as expected.I then insert the 2 arrays into a new array as seen below:
$total = array($person, $hobbies);
using print_r once again returns a new array containing both arrays but it is not associative. However if I try to do the following:
$total = array(
'person' <= $person,
'hobbies' <= $hobbies,
);
and I perform a print_r on $total using the code above I am not seeing both arrays with associations. ^ the above data is just an example data but identical in structure in my real app, I get returned the following result:
Array ( [0] => 1 [1] => 1 )
Once again apologies if I am being extremely thick - which I have a feeling I am.
It sounds like you want the $total array to have person and hobbies keys for the sub-arrays. If so, simply do this:
$total = array("person" => $person, "hobbies" => $hobbies);
Example with output: http://3v4l.org/5U5Hh
Your array assignments are the wrong way round: 'person' <= $person should be 'person' => $person.
// Wrong
$total = array(
'person' <= $person,
'hobbies' <= $hobbies,
);
// Right
$total = array(
'person' => $person,
'hobbies' => $hobbies,
);
You need to use array_merge, if you want to merge both array into a new array.
$result = array_merge($person, $hobbies);

An array of MySQL results...

What am I doing wrong here?
I am attempting to return a json object and I can't seem to get past the array... I've built hundreds of regular array and returned them as a json object but I am having a hard time wrapping my head around this one.
$rows = array();
$post_array = array();
$i = 0;
$result = mysql_query(" SELECT * FROM forum_posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
while($row = mysql_fetch_assoc($result))
{
$post_array[$i] = $rows[ "id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate ];
$i++;
}
It looks like you mean to define an array for $post_array[$i] = .... Like this?
$post_array[$i] = array(
"id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate,
);
(Also, I just took the liberty to respace that a little for readability.)
To convert your array to JSON, pass it to json_encode().
Update: Oh, before you ask about it, I just noticed I added a comma out of habit after the last item in the array. It looks like it's out of place, but it's actually fine to have it there when defining arrays. It doesn't serve any special purpose, but it allows you to copy/paste/remove lines from the array without having to worry about whether or not to add/remove a trailing comma.
As an aside, you don't have to manually increment a numeric array index $i. If you just do this:
$post_array[] = array(...);
it will automatically assign the next available numeric index.
Do you mean do be doing something like this:
$post_array = array();
$i = 0;
$result = mysql_query(" SELECT * FROM forum_posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
while($row = mysql_fetch_assoc($result))
{
$post_array[$i] =array( "id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate );
$i++;
}
Then you can simply use json_encode to encode your array as json.
e.g.
echo json_encode($post_array);
You can't build an array the way you were with $rows[...], you need to use array. Also, instead of managing the ordinals for your array, you can just use array_push

PHP array : simple question about multidimensional array

i've got a SQL query which returns multiple rows, and i have :
$data = array(
"nom" => $row['nom'] ,
"prix" => $row['rapport'],
"average" => "$moyenne_ge"
);
which is perfect, but only if my query returns one row.
i tried that :
$data = array();
$data[$row['nom']]["nom"] = $row['nom'] ;
...
$data[$row['nom']]['average'] = "$moyenne_ge";
in order to have :
$data[brand1][nom] = brand1
$data[brand1][average] = 150$
$data[brand2][nom] = brand2
$data[brand2][average] = 20$
...
but when i do : json_encode($data)
i only have the latest JSON object instead of all JSON object from my request as if my array has only one brand instead of 10.
I guess i did something stupid somewhere.
Thanks for your help
I'd guess that your line:
$data = array();
Is initializing the array on each iteration of your loop. You aren't accumulating more than one row of data.
I guess something like this should work for you:
$resource = mysql_query("YOUR QUERY");
$results = array()
while($result = mysql_fetch_assoc($resource)) {
$results[$result['brand']] = array(
'nom' => $result['nom'],
'prix' => $result['rapport'],
'average' => $moyenne_ge
);
)
$results now contains all the rows from the query indexed by brand. Ask in comments if this wasn't what you're looking for.
If I am reading you right, you should just have to do something like this:
$data[] = array(
"nom" => $row['nom'] ,
"prix" => $row['rapport'],
"average" => "$moyenne_ge"
);
(notice the [])
This should append each array onto $data instead of overwriting the contents.

Categories