Simple question to which I don't have an answer.
How can I change my array from this:
[{"sku":"6"},{"buyers":"7"},{"base":"8"}]
to this:
[{"sku":"6","buyers":"7","base":"8"}]
I have three queries for three different database tables:
$sku = DB::table('mapiranje')->select(DB::raw('count(*) as sku'))
->where('mate_fk', '=', NULL)
->get();
$kupac = DB::table('mapkupci')->select(DB::raw('count(*) as buyers'))
->where('kupci_fk', '=', NULL)
->get();
$base = DB::table('dist_base')->select(DB::raw('count(*) as base'))
->where('base_fk', '=', NULL)
->get();
now each returns:
[{"sku":"6"}]
[{"buyers":"6"}]
[{"base":"6"}]
I have used merge_array to make a single array, but I get:
[{"sku":"6"},{"buyers":"7"},{"base":"8"}]
what I want is:
[{"sku":"6","buyers":"7", "base":"8"}]
-
This question is a little short on information. Can you share what you have tried, and what problems you have run into?Jay Blanchard– Jay Blanchard2015年04月21日 13:28:10 +00:00Commented Apr 21, 2015 at 13:28
-
Also are you talking about changing actual strings or are these string representations of an array/object data structure?Dan Smith– Dan Smith2015年04月21日 13:29:17 +00:00Commented Apr 21, 2015 at 13:29
-
possible duplicate of convert php array into single JSON objectNived– Nived2015年04月21日 13:29:53 +00:00Commented Apr 21, 2015 at 13:29
4 Answers 4
Refactor your code according to right Laravel way:
$result = [
'sku' => DB::table('mapiranje')->whereNull('mate_fk')->count(),
'buyers' => DB::table('mapkupci')->whereNull('kupci_fk')->count(),
'base' => DB::table('dist_base')->whereNull('base_fk')->count()
];
Comments
$result = [];
foreach($input as $oneInputRow) {
$result[$oneInputRow[0]] = $oneInputRow[1];
}
Comments
$target = array();
$start = array(array("sku"=>"6"), "buyers"=>"7"), "base"=>"8"));
foreach($start as $sub){
foreach($sub as $key => $val){
$target[$key] = $val;
}
}
Not shure if laravel provides any special syntax, but just with php I'd do it as above. Basicly you loop over the start-array. In that you loop over every array to get the key/val combination and put that into the target-array. For the second loop there would be other ways if you only have one entry in every secondary array.
Comments
Please try below code
$dd = '[{"sku":"6"},{"buyers":"7"},{"base":"8"}]';
$data = json_decode($dd,true);
$result = array();
foreach($data as $key=>$value){
foreach($value as $key1=>$value1){
$result[$key1] = $value1;
}
}
echo json_encode($result); //this will print your required format result