Daniel
Daniel

Reputation: 11

Transform string from associative array into multidimensional array

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" )
);

Upvotes: 0

Views: 34

Answers (2)

user2560539
user2560539

Reputation:

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

Upvotes: 0

Viktor
Viktor

Reputation: 507

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?

Upvotes: 2

Related Questions