Home > Mobile >  Converting a string with an array structure
Converting a string with an array structure

Time:09-24

I am saving several values in the database. When I output, I get the string ["1"] or ["1", "2"]. How do I convert it to an array so that I can make a selection from the array?

CodePudding user response:

Value has been stored into the database as json string, simply decode the value

$check = '["1", "2"]';
$new = json_decode($check);
print_r($new);

CodePudding user response:

if you use model can try this

protected $casts = [
    'your_db_field_name' => 'array' 
];

and your result try convert it to array. But if you want save array in DB try use JSON format

original material

CodePudding user response:

<?php
$str = 'one,two,three,four';
$count=substr_count($str, ",")  1;
echo $count;
// zero limit
for($i=0;$i<=$count;$i  )
{
$element[]=explode(',',$str,$i);
}
echo"<pre>";
print_r($element[$count]);
?>

CodePudding user response:

You can simply use the str_split function. It makes an array of an string (https://www.php.net/manual/en/function.str-split.php)

In your case it becomes:

$check = '["1", "2"]';
$array = str_split($check);
var_dump($array)
  • Related