Home > Software design >  PHP Convert String formatted like an array to array
PHP Convert String formatted like an array to array

Time:06-26

I have a string like this :

[ 2 => ["Iphone 10", "Iphone 20", "Iphone 30", "Iphone 40"], 3 => ["Mac 10", "Mac 20", "Mac 30", "Mac 40"] ]

I would like to transform it an array . i try to cast it (with (array) in front), but doesn't work. What would be the best way ?

CodePudding user response:

I think the way i get this string is wrong. I decide to edit it, and get a json format in replacement. It's easier to manage then.

CodePudding user response:

I don't know if it's best way but this gives solution to your problem. Here's online example: https://onlinephp.io/c/96a069f5-f11f-4546-86ff-f99ebb3c5800

$string = '[ 2 => ["Iphone 10", "Iphone 20", "Iphone 30", "Iphone 40"], 3 => ["Mac 10", "Mac 20", "Mac 30", "Mac 40"] ]';
$array = explode('"', $string);
$iphones = array_filter($array, function($item) {
    $index = strpos($item, "I");
    if($index !== false) return true;
    return false;
});
$macs = array_filter($array, function($item) {
    $index = strpos($item, "M");
    if($index !== false) return true;
    return false;
});

$outputArray = [1, $iphones, $macs];

unset($outputArray[0]);

var_dump($outputArray);
  • Related