简体   繁体   中英

How can i convert this string type variable in array type?

how can i convert this string in array passing it through a variable?

'NumDoc'=> ['417', '145'], 'dateDoc'=> ['2022-08-12', '2022-08-13'], 'ValueDoc'=> ['100.00', '150.00']

When i try this it works fine:

array('NumDoc'=> ['417', '145'], 'dateDoc'=> ['2022-08-12', '2022-08-13'], 'ValueDoc'=> ['100.00', '150.00'])

But i'm needing to pass it through a variable as below and it's not working:

$string ="'NumDoc'=> ['417', '145'], 'dateDoc'=> ['2022-08-12', '2022-08-13'], 'ValueDoc'=> ['100.00', '150.00']";

array($string);
$string = "'NumDoc'=> ['417', '145'], 'dateDoc'=> ['2022-08-12', '2022-08-13'], 'ValueDoc'=> ['100.00', '150.00']";

function convertToArray(string $string): array
{
  $parts = explode('],', $string);

  foreach($parts as $part) {
    $key = trim(str_replace('\'', '', substr($part, 0, strpos($part, '=>'))));
    $value = trim(substr($part, strpos($part, '=> [') + strlen('=> [')));
  
    $new[str_replace('\'', '', $key)] = explode(',', str_replace(['\'', ' ', ']'], '', $value));
  }

  return $new ?? [];
}

var_dump(convertToArray($string));

Output:

array (size=3)
  'NumDoc' => 
    array (size=2)
      0 => string '417' (length=3)
      1 => string '145' (length=3)
  'dateDoc' => 
    array (size=2)
      0 => string '2022-08-12' (length=10)
      1 => string '2022-08-13' (length=10)
  'ValueDoc' => 
    array (size=2)
      0 => string '100.00' (length=6)
      1 => string '150.00' (length=7)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM