筛选字符串并存储在数组中


Filter a string and store in array

我有一个单字符串。

$a='[{"size":"6Y","quantity":15}]';

我想把6Y和15存储在数组中。请帮帮我。

使用json_decode()

您有一个json编码的字符串。

并且需要对其进行解码,并为数组分配大小和数量。

工作示例:

<?php
$a = '[{"size":"6Y","quantity":15}]';
$b = json_decode($a, TRUE);
$c = array();
if (! empty($b[0])) {
    foreach ($b[0] as $k => $v) {
        $c[$k] = $v;        
    }
}
echo '<pre>';print_r($c);echo '</pre>';
?>  

输出:

Array
(
    [size] => 6Y
    [quantity] => 15
)

将call_user_func_array与array_merge 一起使用

  1. Json解码你的字符串
  2. 展平阵列

像这样:

<?php
$a = '[{"size":"6Y","quantity":15}]';
$b = call_user_func_array('array_merge', json_decode($a,true));
print_r($b);

输出:

Array
(
    [size] => 6Y
    [quantity] => 15
)
$a = '[{"size":"6Y","quantity":15}]';
$v = json_decode($a);
print_r(array_values($v));

试试这个,使用json_decode:

<?php
$a = '[{"size":"6Y","quantity":15}]';
$a = substr($a, 1, -1);
print_r((array)json_decode($a));
?>