How to merge my arrays for DB insertion? - php

I have 2 associative arrays.
Array ( [title1] => test1 [title2] => test2 [title3] => test3 )
and
Array ( [image1] => images1.jpeg [image2] => images2.jpg [image3] => images3.png )
I want to insert each title and image name into database columns(image title and image name).
How it is possible? Anyway to merge them and after that do insertion?

$finalArray = array();
// Use min to avoid improper "OutOfBounds"
$lengthOfArray = min(count($array1), count($array2));
for(i = 1; i <= $lengthOfArray; $i++) {
array_push($finalArray,
array(
'title' => $array1['title' + $i],
'image' => $array2['image' + $i]
)
);
}
With this, in your finalArray you will have tuples of title an image for every database entry.

Look at array_combine()

Maybe instead of combining the arrays, you can use a foreach to construct your query from the two arrays:
//ARRAYS
$a1=array('title1' => 'test1','title2' => 'test2','title3' => 'test3',);
$a2=array('image1' => 'images1.jpeg', 'image2' => 'images2.jpg', 'image3' => 'images3.png');
$fos=''; //we will collect values into this string
foreach ($a1 as $k=>$v) { //we iterate through the first array
$k2=substr($k, 5); //we get the number from the array key (like 2 from title2)
$fos.=empty($fos) ? '' : ', '; //adding commas when needed
$fos.="('{$v}', '{$a2['image'.$k2]}')"; //adding the right values to the values string
}
$q="insert into images (title, filename) values $fos"; //and finishing up the query
In this case the constructed query will be like:
insert into images (title, filename) values
('test1', 'images1.jpeg'),
('test2', 'images2.jpg'),
('test3', 'images3.png')
Note: of course array values need to be correctly escaped for DB usage

array_merge($array1, $array2);

Related

Inserting Array into PHP Array

Working with an array file with following structure. I know there are additional arrays that need to be inserted under each array 'color'.
$items=array (
0 =>
array (
'color' => 'category_a',
),
1 =>
array (
'book' => 'Gone With The Wind',
'movie' => 'GWTW',
'id'=> 'A100'
),
2 =>
array (
'book' => 'Goldfinger',
'movie' => 'GF',
'id'=> 'A103'
),
3 =>
array (
'color' => 'category_b',
),
4 =>
array (
'book' => 'Across The Great Dvide',
'movie' => 'ATGD',
'id'=> 'B102'
),
5 =>
array (
'book' => 'Goldfinger',
'movie' => 'GF',
'id'=> 'B103'
),
);
Once this array is created, I am using a list to loop thru to verify that each value in the list is placed in each 'color' array as follows
foreach ($controllist as $key=>$value){
foreach($items as $item){
if(in_array($value['book'],$item){
echo "PRESENT IN ARRAY"."<BR>";
}else{
echo "INSERT INTO ARRAY HERE"."<BR>";
}
}
}
For simplicity my controllist looks like
Gone With The wind
Across The Great Divide
Goldfinger
Once complete I should end up with the info for Across The Great Divide inserted into 'color'=> 'category a' as the [2] with Goldfinger moving down one. In 'color'=>category_b' the first array should be Gone With The Wind. Any of the 'color' arrays could be missing an array at any position. To sum it up, need to check for the existence of a value from the list, if not present insert into the array. Other than using the foreach loops shown is there an easier way of doing this? If not how can I get the information inserted into the proper position?
Thanks
EDIT:
I believe the question may not be clear. What I need to do is check for the existence of one array in another. If the value in conrollist is not present in the array, insert an array into the array according the position in the conrollist. The inserted array will have the same structure as the others (I can take care of this part). I am having trouble determining if it exist and if not inserting it. Hope this helps
You might want to be using a for loop instead so you have a pointer on each iteration in order to determine where you are in the array.
foreach($items as $item){
for($i = 0; $i < count($controllist); $i++) {
if(in_array($controllist[$i]['book'],$item){
echo "PRESENT IN ARRAY AT POS ".$i."<BR>";
}else{
$controllist[$i]['book'] = $yourvar;
echo "INSERT INTO ARRAY HERE"."<BR>";
}
}
}

Multidimensional array loop php

New to programming so please explain as simply as possible. I have an array as $inputs. That array has rows as row0, row1 and on. Each row has key value pairs such as name='shay', age='23' and a few other things. I need to put those values in a database, but I can't figure out how to get to them and the examples I find go right over my head. I have made a loop with
for ($i = 0, $nums = count($inputs); $i < $nums; $i++)
But once inside of that loop I am lost as to what comes next. Please help.
The array looks as follows:
$inputs =array (
'row' => array (
0 => array ( 'id' => '2869', 'name' => 'shay', 'age' => '23',),
1 => array ( 'id' => '2868', 'name' => 'Tim', 'age' => '30',),
What I need to do is go through and do an insert with $name, $age etc. So I created the for loop, but I have no idea what to do inside of it to get the values of name and age etc for each row. I know how to insert them, it's just getting the values out of the array.
When I use
foreach ($inputs as $key => $row)
I can then do
dd($row['0']);
And return the contents of a row that I would then like to put in my query. I just don't really understand how to go from the dd() to actually accessing the values for each rows in a way that I could insert them.
You can loop over that data like this:
foreach($inputs as $key => $row) {
echo "row $key:\n";
foreach ($row as $person) {
echo " - " . $person['name'], " is ", $person['age'], " old.\n";
}
}
See it run on eval.in
Output based on the input you provided:
row row:
- shay is 23 old.
- Tim is 30 old.

PHP: accessing mysqli result by record id

i'm having an array which contains record ids as follows:
Array
(
[0] => 113
[1] => 43
[2] => 64
)
so for achieving the corresponding records, i'd have to run 3 queries:
select * from mytable where id=113
select * from mytable where id=43
select * from mytable where id=64
my question: wouldn't it be possible executing just ONE query on the whole table then directly access the mysqli result like an associative array by passing the ID?
something like $record = $res['id'][113];?
thanks in advance
You need the IN clause
SELECT * FROM mytable WHERE id IN ( 113,43,64 );
Custom function indexme takes an array of arrays (numeric or associative) and by default gets the first element value of each sub-array and makes it the associative index in a return array. Optionally, a column name can be passed as the second parameter to designate which column value to use for the index.
$array = array(array('id' => 12, 'name' => 'Joe'), array('id' => 9, 'name' => 'Jane'));
$array_keyed = indexme($array);
// > array(12 => array('id' => 12, 'name' => 'Joe'), 9 => array('id' => 9, 'name' => 'Jane'));
print $array_keyed[12]['name'];
// > Joe
function indexme($arr, $key = '') { // <- custom function indexme
$return_arr = array();
if ( '' == $key ) {
$keys = array_keys($arr[0]);
$key = $keys[0];
}
foreach ( $arr as $value ) {
$return_arr[$value[$key]] = $value;
}
return $return_arr;
}
Pass the mysqli response to this function to make an ID indexed array:
$results_keyed = indexme($result->fetch_assoc(), 'id');
Check out the accepted answer on this page MySQL Prepared statements with a variable size variable list for a nice solution to the WHERE IN technique.

Converting array to individual variables

I am using simplehtmldom to parse a webpage and extract a data and then put it in a mysql database. I successfully extracted the data and put it in array but now the problem i am facing is how to convert this array to variable so that I may use it in my database query to insert the record in the specific fields. I want to convert array to individual variables
here is the code
<?php
include("simple_html_dom.php");
$html = file_get_html('abc.html');
$sched = array();
foreach ( $html->find('tr[class=highlight-darkgrey]') as $event ) {
$item['title'] = trim($event->find('td', 1)->plaintext);
$sched[] = $item;
}
var_dump($sched);
?>
and the output is
array (size=6)
0 =>
array (size=1)
'title' => string 'Network admin, field engineer, engineering analyst, sales executive, PA to HR director Required by Telecommunication Company' (length=124)
1 =>
array (size=1)
'title' => string 'Karachi, Hydrabad, Lahore, Rawalpindi, Peshawar, Multan, Faisalabad' (length=67)
2 =>
array (size=1)
'title' => string '5 - 6 Years' (length=11)
3 =>
array (size=1)
'title' => string 'Knowledge of Field' (length=18)
4 =>
array (size=1)
'title' => string '' (length=0)
5 =>
array (size=1)
'title' => string '- Salary and incentives are not full and final. Can be discussed on final interview.
Can please somebody help me in achieving it. Thanks in advance
Well, if this needs to go in specific fields then you can do something like this:
INSERT INTO table_name (column1, column2, column3,...)
VALUES ($sched[0]['title'], $sched[1]['title'], $sched[2]['title'],...);
Php has a function for getting individual variables, extract() http://php.net/manual/en/function.extract.php
However I don't know why you would do that instead of just using a loop to go though your array.
You mean somethign like
foreach($sched as $item) {
$title = $item['title'];
insert_into_db($title);
}
?
Why do you want to move data from one perfectly good location i.e. the array into a scalar variable.
Double your memory usage for no actual reason.
I assume you are going to want to store the title's in a table
So you can :
foreach ( $sched as $one_sched ) {
// do your database update using $one_sched['title'] as the data identifier.
}
Why not use the array values directly? Also to me it makes no sense to build a subarray where every field is called title.
$sched = array();
foreach ( $html->find('tr[class=highlight-darkgrey]') as $event ) {
$sched[] = trim($event->find('td', 1)->plaintext);
}
Then access the values like:
$value0 = $sched[0];
$value1 = $sched[1];
// PDO example
$sth = $dbh->prepare(
'INSERT INTO table VALUES (?, ?, ...)'
);
$sth->execute(array($sched[0], $sched[1], ...));
// or if array count is right
$sth->execute($sched);

Create array from mysql query. Column2 as key Column 1 as value

I have a table that contains
column 1 = state column 2 = link
Alabama auburn.alabama.com
Alabama bham.alabama.com
Alabama dothan.alabama.com
I need to grab from my database table and put into an array that i can array_walk() through. they need to be accessed like this array.
$arraytable = array(
"auburn.alabama.com"=>"Alabama",
"bham.alabama.com"=>"Alabama",
"dothan.alabama.com"=>"Alabama",
);
I have tried everything but not sure how make this work using php to print the array like such. Any help is greatly appreciated.
Note Your question title is inconsistent with your example. In the title you ask for column 1 as the key, but your example uses column 2 as the key. I've used column 2 here...
It isn't clear what MySQL API you are using to fetch, but whichever it is, use the associative fetch method and create new array keys using the pattern $arraytable[$newkey] = $newvalue. This example would be in object-oriented MySQLi:
$arraytable = array();
while($row = $result->fetch_assoc()) {
// Create a new array key with the 'link' and assign the 'state'
$arraytable[$row['link']] = $row['state'];
}
You can use array_column for this, since PHP5.5 (http://php.net/array_column)
Description
array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )
array_column() returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.
For PHP < 5.5:
https://github.com/ramsey/array_column/blob/master/src/array_column.php
To implement AcidReign's suggestion, here is the snippet:
Code: (Demo)
$resultset = [
['state' => 'Alabama', 'link' => 'auburn.alabama.com'],
['state' => 'Alabama', 'link' => 'bham.alabama.com'],
['state' => 'Alabama', 'link' => 'dothan.alabama.com']
];
var_export(array_column($resultset, 'state', 'link'));
// ^^^^-- use this column's data for keys
// ^^^^^-- use this column's data for values
Output:
array (
'auburn.alabama.com' => 'Alabama',
'bham.alabama.com' => 'Alabama',
'dothan.alabama.com' => 'Alabama',
)
However, array_column() won't directly work on a result set object, but a foreach() can immediately access the data set using array syntax without any fetching function calls.
Body-less foreach: (Demo)
$result = [];
foreach ($mysqli->query('SELECT * FROM my_table') as ['link' => $link, 'state' => $result[$link]]);
var_export($result);
Or a foreach with a body: (Demo)
$result = [];
foreach ($mysqli->query('SELECT * FROM my_table') as $row) {
$result[$row['link']] = $row['state'];
}
var_export($result);
All of the above snippets return:
array (
'auburn.alabama.com' => 'Alabama',
'bham.alabama.com' => 'Alabama',
'dothan.alabama.com' => 'Alabama',
)

Categories