0

I'm storing images links into the database separating them with ,, but I want to transform this string into an array, but I'm not sure how to do it.

So my array looks like this:

$array = array(
"name" => "Daniel",
"urls" => "http:/localhost/img/first.png,http://localhost/img/second.png"
);

So I'd like to have it in the following form:

$array2 = array(
"name" => "Daniel",
"urls" => array("http:/localhost/img/first.png",
                "http://localhost/img/second.png" )
);
1

2 Answers 2

2

I haven't been PHP'ing for a while, but for that simple use-case I would use explode.

$array['urls'] = explode(',', $array['urls']);

Uncertain if I interpreted your question correct though?

Sign up to request clarification or add additional context in comments.

3 Comments

Explode will work for his case. Although he really should be storing multiple images in a second table linked by id of the first table. Storing anything in a single field by comma can lead to many issues later with flexibility and maintenance.
Agreed. But you gotta start with something.
If the urls contain comma(s), splitting by comma could be problematic.
0

You can use array_walk_recursive like in the following example.

function url(&$v,$k)
{
    if($k=='urls') {
    $v = explode(",",$v);
    }
}
$array = array(
"name" => "Daniel",
"urls" => "http:/localhost/img/first.png,http://localhost/img/second.png"
);
array_walk_recursive($array,"url");

You can check the output on PHP Sandbox

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.