php insert array into array
Как в php добавить к массиву другой массив?
Для преобразования массивов в php есть множество функций и операторов: Сборник функций для работы с массивами
Есть несколько способов, чтобы добавить массив в массив при помощи php и все они могут пригодиться для отдельных случаев.
«Оператор +»
Это простой, но коварный способ:
А теперь более подробный пример, чтобы проиллюстрировать это:
Функция array_merge()
Использовать эту функцию можно следующим образом:
Она сбрасывает числовые индексы и заменяет строковые. Отлично подходит для того, чтобы склеить два или несколько массивов с числовыми индексами:
Если входные массивы имеют одинаковые строковые ключи, тогда каждое последующее значение будет заменять предыдущее. Однако, если массивы имеют одинаковые числовые ключи, значение, упомянутое последним, не заменит исходное значение, а будет добавлено в конец массива.
Функция array_merge_recursive
Делает то же самое, что и array_merge только еще и рекурсивно проходит по каждой ветке массива и проделывает то же самое с потомками. Подробная справка по array_merge_recursive
Функция array_replace()
Заменяет элементы массива элементами других переданных массивов. Подробная справка по array_replace.
Функция array_replace_recursive()
То же что и array_replace только обрабатывает все ветки массива. Справка по array_replace_recursive.
Insert into array at a specified place
J is the son of C. update array so:
how do I insert J after C in the array?
I also map the array in a loop (array of comments for display). Will this method take a very long time to perform?
5 Answers 5
Use the splice function to solve this.
It would be more accurate as follows:
But thanks @Pekka for getting me 95% of the way there!
You can use the splice function:
I wrote a function to insert into an array at a specified index:
It will also work for multidimensional arrays but only with a numerical key.
Not the answer you’re looking for? Browse other questions tagged php or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
array_push
(PHP 4, PHP 5, PHP 7, PHP 8)
array_push — Добавляет один или несколько элементов в конец массива
Описание
Список параметров
Возвращаемые значения
Возвращает новое количество элементов в массиве.
Список изменений
Версия | Описание |
---|---|
7.3.0 | Теперь эта функция может быть вызвана с одним параметром. Ранее требовалось минимум два параметра. |
Примеры
Пример #1 Пример использования array_push()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 35 notes
If you’re going to use array_push() to insert a «$key» => «$value» pair into an array, it can be done using the following:
It is not necessary to use array_push.
Hope this helps someone.
Rodrigo de Aquino asserted that instead of using array_push to append to an associative array you can instead just do.
. but this is actually not true. Unlike array_push and even.
. Rodrigo’s suggestion is NOT guaranteed to append the new element to the END of the array. For instance.
$data[‘one’] = 1;
$data[‘two’] = 2;
$data[‘three’] = 3;
$data[‘four’] = 4;
. might very well result in an array that looks like this.
[ «four» => 4, «one» => 1, «three» => 3, «two» => 2 ]
I can only assume that PHP sorts the array as elements are added to make it easier for it to find a specified element by its key later. In many cases it won’t matter if the array is not stored internally in the same order you added the elements, but if, for instance, you execute a foreach on the array later, the elements may not be processed in the order you need them to be.
If you want to add elements to the END of an associative array you should use the unary array union operator (+=) instead.
$data[‘one’] = 1;
$data += [ «two» => 2 ];
$data += [ «three» => 3 ];
$data += [ «four» => 4 ];
You can also, of course, append more than one element at once.
$data[‘one’] = 1;
$data += [ «two» => 2, «three» => 3 ];
$data += [ «four» => 4 ];
. which will result in an array that looks like this.
[ «element1» => 1, «element2» => 2, «element3» => 3, «element4» => 4 ]
This is how I add all the elements from one array to another:
If you’re adding multiple values to an array in a loop, it’s faster to use array_push than repeated [] = statements that I see all the time:
$ php5 arraypush.php
X-Powered-By: PHP/5.2.5
Content-type: text/html
Adding 100k elements to array with []
Adding 100k elements to array with array_push
Adding 100k elements to array with [] 10 per iteration
Adding 100k elements to array with array_push 10 per iteration
?>
The above will output this:
Array (
[0] => a
[1] => b
[2] => c
[3] => Array (
[0] => a
[1] => b
[2] => c
)
)
There is a mistake in the note by egingell at sisna dot com 12 years ago. The tow dimensional array will output «d,e,f», not «a,b,c».
Need a real one-liner for adding an element onto a new array name?
Skylifter notes on 20-Jan-2004 that the [] empty bracket notation does not return the array count as array_push does. There’s another difference between array_push and the recommended empty bracket notation.
Empy bracket doesn’t check if a variable is an array first as array_push does. If array_push finds that a variable isn’t an array it prints a Warning message if E_ALL error reporting is on.
So array_push is safer than [], until further this is changed by the PHP developers.
If you want to preserve the keys in the array, use the following:
elegant php array combinations algorithm
A common operation when pushing a value onto a stack is to address the value at the top of the stack.
This can be done easily using the ‘end’ function:
A function which mimics push() from perl, perl lets you push an array to an array: push(@array, @array2, @array3). This function mimics that behaviour.
Add elements to an array before or after a specific index or key:
Insert new item in array on any position in PHP
How can I insert a new item into an array on any position, for example in the middle of array?
22 Answers 22
You may find this a little more intuitive. It only requires one function call to array_splice :
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.
A function that can insert at both integer and string positions:
There is no native PHP function (that I am aware of) that can do exactly what you requested.
I’ve written 2 methods that I believe are fit for purpose:
While faster and probably more memory efficient, this is only really suitable where it is not necessary to maintain the keys of the array.
If you do need to maintain keys, the following would be more suitable;
This way you can insert arrays:
If you want to keep the keys of the initial array and also add an array that has keys, then use the function below:
Based on @Halil great answer, here is simple function how to insert new element after a specific key, while preserving integer keys:
This is what worked for me for the associative array:
This is also a working solution:
if unsure, then DONT USE THESE:
because with + original array will be overwritten. (see source)
Solution by jay.lee is perfect. In case you want to add item(s) to a multidimensional array, first add a single dimensional array and then replace it afterwards.
Adding an item in same format to this array will add all new array indexes as items instead of just item.
Note: Adding items directly to a multidimensional array with array_splice will add all its indexes as items instead of just that item.
Hint for adding an element at the beginning of an array:
Insert array into MySQL database with PHP
I have the following array I want to store in my database.
I’ve tried searching google on how to do this and all I can find is information stating my array needs to be split, before inserting into the table. Is this correct? Sorry for the naivity, very new to php.
21 Answers 21
You can not insert an array directly to MySQL as MySQL doesn’t understand PHP data types. MySQL only understands SQL. So to insert an array into a MySQL database you have to convert it to a SQL statement. This can be done manually or by a library. The output should be an INSERT statement.
Since PHP 5.5 mysql_real_escape_string has been deprecated and as of PHP7 it has been removed. See: php.net’s documentation on the new procedure.
Original answer:
Here is a standard MySQL insert statement.
If you have a table with name fbdata with the columns which are presented in the keys of your array you can insert with this small snippet. Here is how your array is converted to this statement.
There are a number of different ways. I will give you an example of one using prepared statements:
I’m cheating here and assuming the keys in your first array are the column names in the SQL table. I’m also assuming you have PDO available. More can be found at http://php.net/manual/en/book.pdo.php
Here is my full solution to this based on the accepted answer.
db.php
dbSettings.php
Personally I’d json_encode the array (taking into account any escaping etc needed) and bung the entire lot into an appropriately sized text/blob field.
It makes it very easy to store «unstructured» data but a real PITA to search/index on with any grace.
A simple json_decode will «explode» the data back into an array for you.
Serialize the array and you’ll have a text on your database column, that will solve the problem.
I do that, for instance to save objects, that way I can retrieve them easily.
Only need to write this line to insert an array into a database.
implode(‘, ‘,array_keys($insData)) : Gives you all keys as string format
implode(‘, ‘,array_values($insData)) : Gives you all values as string format
You have 2 ways of doing it:
This is improvement to the solution given by Shiplu Mokaddim
Insert array data into mysql php
I Have array data.. I want post that data in database
1: this is my array data:
code used i used to insert that data:
I search about the same problem, but I wanted to store the array in a filed not to add the array as a tuple, so you may need the function serialize() and unserialize().
Maybe it will be to complex for this question but it surely do the job for you. I have created two classes to handle not only array insertion but also querying the database, updating and deleting files. «MySqliConnection» class is used to create only one instance of db connection (to prevent duplication of new objects).
The second «TableManager» class is little bit more complex. It also make use of the MySqliConnection class which I posted above. So you would have to include both of them in your project. TableManager will allow you to easy make insertion updates and deletions. Class have separate placeholder for read and write.