我在MySQL中有数据。该数据由json数据创建。但是我不能从数据键更改为数组。我想根据库存数量顺序设置此数据。
[
{"size":"36","stock":"1"},
{"size":"37","stock":"2"},
{"size":"38","stock":"1"},
{"size":"40","stock":"1"},
{"size":"36","stock":"1"},
{"size":"37","stock":"3"},
{"size":"38","stock":"2"},
{"size":"39","stock":"3"},
{"size":"40","stock":"2"}
]
我想更改为:
array(
'36' => '2',
'37' => '5',
'38' => '3',
'39' => '3',
'40' => '3',
)
我编写了此函数,但它仅返回true
,并且我认为它可以进一步完善:
function shoesizes($json,$key='size')
{
$array = json_decode($json);
$result = array();
$sum = 0;
$i=0;
foreach((array) $array as $val) {
if(array_key_exists($key, $val)){
$result[$val->$key][] = (array)$val;
}else{
$result[""][] = $val;
}
}
$arrsi = array();
foreach ($result as $k => $v) {
$sum = 0;
foreach ($v as $c => $d) {
$sum += $d['stock'];
}
$arrsi[$k]= $sum;
}
return ksort($arrsi);
}
答案 0 :(得分:0)
解码然后迭代数组。如果第一次出现size
,则存储整数值;否则,将新值添加到存储的值中。完成后,按结果数组键排序。
代码:(Demo)
$json = '[
{"size":"36","stock":"1"},
{"size":"37","stock":"2"},
{"size":"38","stock":"1"},
{"size":"40","stock":"1"},
{"size":"36","stock":"1"},
{"size":"37","stock":"3"},
{"size":"38","stock":"2"},
{"size":"39","stock":"3"},
{"size":"40","stock":"2"}
]';
$array = json_decode($json, true);
foreach ($array as $row) {
if (isset($result[$row['size']])) {
$result[$row['size']] += $row['stock'];
} else {
$result[$row['size']] = (int)$row['stock'];
}
}
ksort($result);
var_export($result);
输出:
array (
36 => 2,
37 => 5,
38 => 3,
39 => 3,
40 => 3,
)
代码查看:
ksort()
返回布尔结果。通过编写return ksort($arrsi);
,您只能收到true
或false
(并且false
仅在发生故障时可以发生)。 http://php.net/manual/en/function.ksort.php一旦写了ksort($arrsi);
然后写了return $arrsi;
,函数就会返回所需的结果。$i
,以便可以安全地删除该行。$sum = 0;
的第一个声明不是必需的,因为稍后在第二个循环中重新声明了变量。size
值分配为键当然是正确的步骤。将每个日期集存储为新密钥的子数组比您所需要的更多。这导致您必须遵循嵌套循环。