ChatGPT解决这个技术问题 Extra ChatGPT

Convert flat array to a delimited string to be saved in the database

What is the best method for converting a PHP array into a string?
I have the variable $type which is an array of types.

$type = $_POST[type];

I want to store it as a single string in my database with each entry separated by | :

Sports|Festivals|Other
Please refrain from inserting serialized values into a database. Here's why: stackoverflow.com/questions/7364803/…
@NullUserExceptionఠ_ఠ I agree that inserting serialized values into the DB just absolutely burns eyes, but you don't know his situation - it very well maybe warranted.
I think that this question should be reopened. It is useful question for beginners and I don't think it is off-topic.
what if some of the values in array have chars |
You can then escape those characters. Read it in here. php.net/manual/en/regexp.reference.escape.php

K
Kees de Kooter

Use implode

implode("|",$type);

This is good unless you have nested arrays - which can happen with $_POST if you're using array-named form inputs.
with nested arrays just use a foreach it will work.
@devasia2112 foreach for nested array will not be a good/efficient solution.... if it is multi level nested ? and if somewhere depth is 2 and some where 3 ? it will be too much overhead and program complexity will be worse in that case ! Serializing is far better in this case.
J
Jakub

You can use json_encode()

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>

Later just use json_decode() to decode the string from your DB. Anything else is useless, JSON keeps the array relationship intact for later usage!


"Anything else is useless"... except perhaps normalizing the data.
Rofl @ comment above me. As you say, blanket statements are almost always, unhelpful.
I'm glad you guys are entertained :)
"Sweeping generalizations, as well as absolutes, are always wrong. Always." ;)
I like that this one keeps the keys. This is very useful for later use.
S
Sumit Kumar
json_encode($data) //converts an array to JSON string
json_decode($jsonString) //converts json string to php array

WHY JSON : You can use it with most of the programming languages, string created by serialize() function of php is readable in PHP only, and you will not like to store such things in your databases specially if database is shared among applications written in different programming languages


JFI in my use I had to call $data= json_decode($jsonString, true)
second argument is optional, in most of the case it works without that.
This works for single or multi dimension arrays excellent and in my opinion this should be the accepted answer. Also consider adding true as a second parameter.
T
T.Todua

One of the Best way:

echo print_r($array, true);

please elaborate on your answer, showing how it solves the problem
You can also use: "print_r($array, false);", as this will print the array without returning a value. If true is given, print_r() won't print on it's own and will simply return the string. More at: php.net/manual/en/function.print-r.php
This one should be the best one since json_decode messes up with the format causing confusion.
it was requested to store the string in the db, not to print it
N
Nisse Engström

No, you don't want to store it as a single string in your database like that.

You could use serialize() but this will make your data harder to search, harder to work with, and wastes space.

You could do some other encoding as well, but it's generally prone to the same problem.

The whole reason you have a DB is so you can accomplish work like this trivially. You don't need a table to store arrays, you need a table that you can represent as an array.

Example:

id | word
1  | Sports
2  | Festivals
3  | Classes
4  | Other

You would simply select the data from the table with SQL, rather than have a table that looks like:

id | word
1  | Sports|Festivals|Classes|Other

That's not how anybody designs a schema in a relational database, it totally defeats the purpose of it.


sure it is, you dont have to escape the delimiters!
@MarcB It makes the encoding idiot-proof, standard, prone to less bugs, and easily exportable back to an array. Should he use another table? Probably. Is this better than everyone saying implode? Absolutely.
The right answer to this question would be: don't insert serialized values in an RDBMS. This is the kind of thing that should summon raptors.
@timdev: json-escaping may in some situations correspond to SQL escaping, but depending on that will just burn you in the end. JSON uses backslashes - what if you're on a DB that doesn't recognizes backslashes and uses doubled-quotes for escape? e.g. '' instead of \'?
While I agree with the principle expressed here (normal forms are good, using DB to structure is good, duh), any answer that starts with "No, you don't want..." sets off bells in my head. You do not have the full context of the asker's question, and believe it or not, they might just have an excellent reason to denormalize this particular data and store it in a single field. No, you are not omniscient; you do NOT know what the asker wants. Put your opinions in a comment, not an answer, please.
t
timdev

implode():

<?php
$string = implode('|',$types);

However, Incognito is right, you probably don't want to store it that way -- it's a total waste of the relational power of your database.

If you're dead-set on serializing, you might also consider using json_encode()


implode is limited to flat arrays
T
T.Todua

This one saves KEYS & VALUES

function array2string($data){
    $log_a = "";
    foreach ($data as $key => $value) {
        if(is_array($value))    $log_a .= "[".$key."] => (". array2string($value). ") \n";
        else                    $log_a .= "[".$key."] => ".$value."\n";
    }
    return $log_a;
}

Hope it helps someone.


s
slfan
$data = array("asdcasdc","35353","asdca353sdc","sadcasdc","sadcasdc","asdcsdcsad");

$string_array = json_encode($data);

now you can insert this $string_array value into Database


G
Guilherme Nascimento

For store associative arrays you can use serialize:

$arr = array(
    'a' => 1,
    'b' => 2,
    'c' => 3
);

file_put_contents('stored-array.txt', serialize($arr));

And load using unserialize:

$arr = unserialize(file_get_contents('stored-array.txt'));

print_r($arr);

But if need creat dinamic .php files with array (for example config files), you can use var_export(..., true);, like this:

Save in file:

$arr = array(
    'a' => 1,
    'b' => 2,
    'c' => 3
);

$str = preg_replace('#,(\s+|)\)#', '$1)', var_export($arr, true));
$str = '<?php' . PHP_EOL . 'return ' . $str . ';';

file_put_contents('config.php', $str);

Get array values:

$arr = include 'config.php';

print_r($arr);

H
HOSSEIN B

You can use serialize:

$array = array('text' => 'Hello world', 'value' => 100);
$string = serialize($array); // a:2:{s:4:"text";s:11:"Hello world";s:5:"value";i:100;}

and use unserialize to convert string to array:

$string = 'a:2:{s:4:"text";s:11:"Hello world";s:5:"value";i:100;}';
$array = unserialize($string); // 'text' => 'Hello world', 'value' => 100

A
Akbar Mirsiddikov

there are many ways ,

two best ways for this are

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
//ouputs as
{"a":1,"b":2,"c":3,"d":4,"e":5}


$b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z'));
$results = print_r($b, true); // $results now contains output from print_r

You're repeating answers that were already given. This does not add new value or new methods.
@Tschallacka yeah but very few answers on this post provide output ....
S
Serhii Popov

Yet another way, PHP var_export() with short array syntax (square brackets) indented 4 spaces:

function varExport($expression, $return = true) {
    $export = var_export($expression, true);
    $export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
    $array = preg_split("/\r\n|\n|\r/", $export);
    $array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [null, ']$1', ' => ['], $array);
    $export = join(PHP_EOL, array_filter(["["] + $array));
    
    if ((bool) $return) return $export; else echo $export;
}

Taken here.


Please read about what \R does in regex.
A
Arvy

If you have an array (like $_POST) and need to keep keys and values:

function array_to_string($array) {
   foreach ($array as $a=>$b) $c[]=$a.'='.$b;
   return implode(', ',$c);
}

Result like: "name=Paul, age=23, city=Chicago"


H
Hashan
$types = ['a','b','c'];
$string = implode(",",$types);
echo $string;

answer = "a,b,c".


Printing an imploded string was already recommended by multiple answers on this page more than a decade earlier. Please only post a new answer if you have something unique and valuable to add to the page (and always explain your code -- a demonstration is not an explanation).