Viewed   75 times

How can I insert a new item into an array on any position, for example in the middle of array?

 Answers

5

You may find this a little more intuitive. It only requires one function call to array_splice:

$original = array( 'a', 'b', 'c', 'd', 'e' );
$inserted = array( 'x' ); // not necessarily an array, see manual quote

array_splice( $original, 3, 0, $inserted ); // splice in at position 3
// $original is now a b c x d e

If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL.

Wednesday, October 5, 2022
2

I would say just build it yourself. You can set it up like this:

$query = "INSERT INTO x (a,b,c) VALUES ";
foreach ($arr as $item) {
  $query .= "('".$item[0]."','".$item[1]."','".$item[2]."'),";
}
$query = rtrim($query,",");//remove the extra comma
//execute query

Don't forget to escape quotes if it's necessary.

Also, be careful that there's not too much data being sent at once. You may have to execute it in chunks instead of all at once.

Saturday, November 5, 2022
4

Your main issue is, declaring $query outside the loop. It makes it a constant, and that too, takes values $a and $b which are that time, undefined, so results in invalid syntax for SQL.

foreach($Cust_PN as $a => $b) {
   $query1 = "INSERT INTO SO_Items (Timestamp, SO_Num, SO_Rev, SO_Line_Item, Cust_PN, Cust_PN_Rev, My_PN, My_PN_Rev, Description, Qty, Sale_Price, UOM, Program, Required_Date) VALUES (NOW(), '$SO_Num', '$SO_Rev', '$SO_Line_Item[$a]', '$Cust_PN[$a]', '$Cust_PN_Rev[$a]', '$My_PN[$a]', '$My_PN_Rev[$a]', '$Description[$a]', '$Qty[$a]', '$Sale_Price[$a]', '$UOM[$a]', '$Program[$a]', '$Required_Date[$a]');";

   $q = mysql_query($query1) or die ('Error posting data');

 }

Try that. Fixed your SQL query too. Correct syntax is

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

You had put SELECT in place of VALUES

Let me know if it works, and otherwise please tell what error it ives exactly.

Sunday, November 27, 2022
 
moss
 
4
<input type="number" name="unos[]">
<input type="number" name="unos[]">
<input type="number" name="unos[]">
etc.

The above is standard for pulling form values into an array, but, given your update:

// Assuming "," separated values
   $unos = explode(",", $_POST['unos']);

   foreach ($unos as $item) {
       echo $item; // Do something with item
   }
Saturday, October 1, 2022
 
1

you could indeed use PHP's array_map() to do this

function cb($obj) { return $obj->myMethod(); }
.
.
$data = array_map(cb, $objects);
Tuesday, November 29, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :