I have the following PHP code on my website:
<?php
$FirstName = array("Jacob", "Noah", "Frank");
$LastName = array("Collins", "Little", "Allen");
$BirthDay = array(19, 31, 06);
?>
And I want it to be output like so:
("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06)
for an SQL string, which will be:
INSERT INTO Users (FirstName, LastName, BirthDay) VALUES ("Jacob", "Collins", 19), ("Noah", "Little", 31), ("Frank", "Allen", 06);
I am quite new to PHP (only started yesterday) and was wondering how I would do this.
Thanks.
Simply, If you have same count of $FirstName
, $LastName
and $BirthDay
,
using for
loop and array_push
you can do it like this:
$data = array();
$count = count($FirstName);
for($i = 0; $i < $count; $i++ ){
$insert = [$FirstName[$i],$LastName[$i], $BirthDay[$i]];
array_push($data,$insert);
}
The $data
gives you formatted array.
Since you're just new to PHP, let's not yet get into classes.
An easy way to do this, without destroying or modifying the data you are storing is by using a multidimensional array, like this :
$myArray = array(
array( "Jacob", "Collins", 19 ),
array( "Noah", "Little", 31 )
);
// Displays "Noah little 31"
echo $myArray[1][0]." ".$myArray[1][1]." ".$myArray[1][2];
foreach ($myArray as $row)
{
//concatenate this to your query string.
$assembledQuery = "(\"$row[0]\", \"$row[1]\", $row[2])";
}
However, PLEASE keep in mind that this way of building queries is VERY VERY dangerous!
you can do using for loops
<?php
$FirstName = array("Jacob", "Noah", "Frank");
$LastName = array("Collins", "Little", "Allen");
$BirthDay = array(19, 31, 06);
$length = count($FirstName);
for($x=0;$x<$length;$x++)
{
$custom = array();
$f = $FirstName[$x];
$l = $LastName[$x];
$b = $BirthDay[$x];
array_push($custom,$f);
array_push($custom,$l);
array_push($custom,$b);
print_r($custom);
}
?>
Hope this helps..!
below code is help you when birthday or lastname is not in array
$data = [];
$total = count($FirstName);
for($i = 0;$i < $total;$i++) {
$tmp = [];
$tmp[] = (isset($FirstName[$i]))? $FirstName[$i] : "";
$tmp[] = (isset($LastName[$i]))? $LastName[$i] : "";
$tmp[] = (isset($BirthDay[$i]))? $BirthDay[$i] : "";
$data[] = $tmp;
}
// $data is array what you want i have just dump the $data
echo "<pre>";
var_dump($data);