I have data in MySQL. The data is created by json datas. But I can't change to array from data keys. I want to set this data in order and according to the number of stock.
[
{"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"}
]
I want change to:
array(
'36' => '2',
'37' => '5',
'38' => '3',
'39' => '3',
'40' => '3',
)
I wrote this function but it only returns true
and I feel it could be more refined:
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);
}
Decode then iterate the array. If the first occurrence of size
store the integer value, if not add the new value to the stored value. When done, sort by the result array keys.
Code: (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);
Output:
array (
36 => 2,
37 => 5,
38 => 3,
39 => 3,
40 => 3,
)
Code Review:
ksort()
returns a boolean result. By writing return ksort($arrsi);
, you can only receive true
or false
(and false
can only happen when there is a failure). http://php.net/manual/en/function.ksort.php Once you write ksort($arrsi);
then return $arrsi;
then your function returns the desired result.$i
so that line can be safely removed.$sum = 0;
isn't necessary because you redeclare the variable later in your second loop.size
values as keys is certainly the right step. Storing each set of date as a subarray of the new key is more than what you need. This causes you to have to follow up with a nested loop.