Как из строки сделать массив php
Перейти к содержимому

Как из строки сделать массив php

PHP: конвертирование массива в строку

В этой статье разберем как преобразовывать массив в строку и обратно.

Есть два способа преобразовать массив в строку в PHP.

  1. Использование функции implode()
  2. Использование функции json_encode()

Использование функции implode()

Используя функцию implode(), мы можем преобразовать все элементы массива в строку. Параметр разделителя в функции implode() является необязательным. Но хорошей практикой будет использовать оба аргумента.

В приведенном выше примере в первой строке объявлена ​​переменная массива и ей присвоены некоторые значения.

На следующей строке функция implode() преобразует массив в строку. Два параметра передаются в функцию implode(). Первый — это разделитель, а второй — массив.

Вы также можете преобразовать полученную строку если требуется обратно в массив. Для этого мы можем использовать функцию PHP explode().

Функция explode()

Используя функцию explode(), мы можем преобразовать строку в элементы массива. Мы можем передать три аргумента. Первый разделитель, второй массив и последний лимит (ограничение длинны).

В приведенном выше примере строковой переменной присваивается некоторое значение. Затем функция explode() разбивает эту строку на массив. После этого мы использовали функцию print_r(), которая печатает все элементы массива и его индексы.

Использование функции json()

В PHP объекты могут быть преобразованы в строку JSON с помощью функции json_encode().

Обычное использование JSON — это чтение данных с веб-сервера и отображение данных на веб-странице.

В приведенном выше примере мы присвоили значение переменной объекта, а затем в json_encode() преобразовали значение в переменную массива и создали ассоциативный массив.

Создать массив из строки с разделителями explode() в php

4324234

Рассмотрим популярный способ создания массива из строки за счет разделителя, которым может быть практически любой символ, а также обратную этому методу операцию.

Для решения данных задач нам потребуются две php функции explode() и implode(). Начнем с первой.

explode() — возвращает массив строк, полученных разбиением строки с использованием разделителя.
Синтаксис: explode (разделитель, строка);

Данная функцию я часто использую при выгрузке из БД, например, если в каком-то столбике записаны все данные через точку с запятой. Чаще всего это бывают параметры — цвет, вес, url адрес и т.п.

Пример использования:
<?php
$pizza = «кусок1;кусок2;кусок3;кусок4;кусок5;кусок6»;
$pieces = explode(«;», $pizza);
echo $pieces[0]; // кусок1
echo $pieces[1]; // кусок2
?>

В этом примере строка $pizza имеет значения кусок, которые «разделены» между собой точкой с запятой. При запуске explode(«;», $pizza) в кавычках указан именно этот разделитель, поэтому в переменную $pieces, будут записываться элементы массива кусок1, кусок2 и т.д.

Разделителем может быть практически любой символ или их сочетание. Создавайте разделители уникальными, если они могут встречаться в текст, например: razde, identif и т.п.

Создать строку из массива

implode() — объединяет элементы массива в строку с разделителем.

Эта функция является обратной explode(). Ее можно использовать в разных областях, в том числе и при записи данных в БД.

Синтаксис: implode (разделитель, массив);

Пример:
<?php $array = array(‘lastname’, ’email’, ‘phone’);
$comma_separated = implode(«,», $array);
echo $comma_separated;
?>

В этом примере мы имеем массив $array, который превращаем в одну строку, где каждый элемент массива прописан с разделителем. На выходе мы получим строку: lastname,email,phone.

Как из строки сделать массив php

I think your first, main example is needlessly confusing, very confusing to newbies:

It should be removed.

For newbies:
An array index can be any string value, even a value that is also a value in the array.
The value of array[«foo»] is «bar».
The value of array[«bar»] is «foo»

The following expressions are both true:
$array[«foo»] == «bar»
$array[«bar»] == «foo»

Since PHP 7.1, the string will not be converted to array automatically.

Below codes will fail:

$a=array();
$a[‘a’]=»;
$a[‘a’][‘b’]=»;
//Warning: Illegal string offset ‘b’
//Warning: Cannot assign an empty string to a string offset

You have to change to as below:

$a[‘a’]=array(); // Declare it is an array first
$a[‘a’][‘b’]=»;

«If you convert a NULL value to an array, you get an empty array.»

This turns out to be a useful property. Say you have a search function that returns an array of values on success or NULL if nothing found.

<?php $values = search (. ); ?>

Now you want to merge the array with another array. What do we do if $values is NULL? No problem:

<?php $combined = array_merge ((array) $values , $other ); ?>

Voila.

Beware that if you’re using strings as indices in the $_POST array, that periods are transformed into underscores:

<html>
<body>
<?php
printf ( «POST: » ); print_r ( $_POST ); printf ( «<br/>» );
?>
<form method=»post» action default»><?php echo $_SERVER [ ‘PHP_SELF’ ]; ?> «>
<input type=»hidden» name=»Windows3.1″ value=»Sux»>
<input type=»submit» value=»Click» />
</form>
</body>
</html>

Once you click on the button, the page displays the following:

POST: Array ( [Windows3_1] => Sux )

— quote —
Note:
Both square brackets and curly braces can be used interchangeably for accessing array elements
— quote end —

At least for php 5.4 and 5.6; if function returns an array, the curly brackets does not work directly accessing function result, eg. WillReturnArray() <1>. This will give «syntax error, unexpected ‘<' in. ".
Personally I use only square brackets, expect for accessing single char in string. Old habits.

Note that array value buckets are reference-safe, even through serialization.

<?php
$x = ‘initial’ ;
$test =array( ‘A’ =>& $x , ‘B’ =>& $x );
$test = unserialize ( serialize ( $test ));
$test [ ‘A’ ]= ‘changed’ ;
echo $test [ ‘B’ ]; // Outputs «changed»
?>

This can be useful in some cases, for example saving RAM within complex structures.

Regarding the previous comment, beware of the fact that reference to the last value of the array remains stored in $value after the foreach:

<?php
foreach ( $arr as $key => & $value )
<
$value = 1 ;
>

// without next line you can get bad results.
//unset( $value );

$value = 159 ;
?>

Now the last element of $arr has the value of ‘159’. If we remove the comment in the unset() line, everything works as expected ($arr has all values of ‘1’).

Bad results can also appear in nested foreach loops (the same reason as above).

So either unset $value after each foreach or better use the longer form:

//array keys are always integer and string data type and array values are all data type
//type casting and overwriting(data type of array key)
//—————————————————-
$arr = array(
1=>»a»,//int(1)
«3»=>»b»,//int(3)
«08»=>»c»,//string(2)»08″
«80»=>»d»,//int(80)
«0»=>»e»,//int(0)
«Hellow»=>»f»,//string(6)»Hellow»
«10Hellow»=>»h»,//string(8)»10Hellow»
1.5=>»j»,//int(1.5)
«1.5»=>»k»,//string(3)»1.5″
0.0=>»l»,//int(0)
false=>»m»,//int(false)
true=>»n»,//int(true)
«true»=>»o»,//string(4)»true»
«false»=>»p»,//string(5)»false»
null=>»q»,//string(0)»»
NULL=>»r»,//string(0)»» note null and NULL are same
«NULL»=>»s»,//string(4)»NULL» . In last element of multiline array,comma is better to used.
);
//check the data type name of key
foreach ($arr as $key => $value) <
var_dump($key);
echo «<br>»;
>

//NOte :array and object data type in keys are Illegal ofset.

[Editor’s note: You can achieve what you’re looking for by referencing $single, rather than copying it by value in your foreach statement. See http://php.net/foreach for more details.]

Don’t know if this is known or not, but it did eat some of my time and maybe it won’t eat your time now.

I tried to add something to a multidimensional array, but that didn’t work at first, look at the code below to see what I mean:

$a1 = array( «a» => 0 , «b» => 1 );
$a2 = array( «aa» => 00 , «bb» => 11 );

$together = array( $a1 , $a2 );

foreach( $together as $single ) <
$single [ «c» ] = 3 ;
>

foreach( $together as $key => $value ) <
$together [ $key ][ «c» ] = 3 ;
>

// Before php 5.4
$array = array(1,2,3);

// since php 5.4 , short syntax
$array = [1,2,3];

// I recommend using the short syntax if you have php version >= 5.4

Used to creating arrays like this in Perl?

Looks like we need the range() function in PHP:

<?php
$array = array_merge (array( ‘All’ ), range ( ‘A’ , ‘Z’ ));
?>

You don’t need to array_merge if it’s just one range:

Function unset can delete array’s element by reference only when you specify source array. See example:
<?php
$array = [ 1 , 2 , 3 , 4 , 5 ];
foreach ( $array as $k => & $v ) <
if ( $k >= 3 ) <
unset( $v );
>
>
echo count ( $array ); // 5
?>
In this case unset delete only reference, however original array didn’t change.

Or different example:
<?php
$arr = [ 1 , 2 ];
$a = & $arr [ 0 ];
unset( $a );
count ( $arr ); // 2
?>

So for deleting element from first example need use key and array.
<?php
// .
unset( $array [ $k ]);
// .
?>

There is another kind of array (php>= 5.3.0) produced by

$array = new SplFixedArray(5);

Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.

Supposing a large string-keyed array

$arr=[‘string1’=>$data1, ‘string2’=>$data2 etc. ]

when getting the keyed data with

php does *not* have to search through the array comparing each key string to the given key (‘string1’) one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it’s all hidden away.

However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :

Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It’s also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *