Hi I'am trying to get data Array and looping with For. So I have array called 'color' and I want loop the Array with For. But I have some trouble in the result. I've been tried change the array and in foreach but I got no idea how to get result like what I want.
The Result :
"data": [
{
"title": "get data users",
"function_name": "selectDataUser",
"function_drop": "selectDataUser",
"type_of_chart": "Pie",
"embed": null,
"created_at": "2019-06-15 03:26:09.000",
"updated_at": null,
"data_chart": [
{
"name": "Administrator",
"total": "100",
"color": "0xFF888888" //color cannot be the same
},
{
"name": "Staff",
"total": "100",
"color": "0xFF888888" //the color must be different
},
{
"name": "Super Administrator",
"total": "1",
"color": "0xFF888888" //this is not result what I want.
}
],
}
]
I want response like this:
"data": [
{
"title": "get data users",
"function_name": "selectDataUser",
"function_drop": "selectDataUser",
"type_of_chart": "Pie",
"embed": null,
"created_at": "2019-06-15 03:26:09.000",
"updated_at": null,
"data_chart": [
{
"name": "Administrator",
"total": "100",
"color": "0xFF000000" //all this color different
},
{
"name": "Staff",
"total": "100",
"color": "0xFF444444" //the color different
},
{
"name": "Super Administrator",
"total": "1",
"color": "0xFF888888" //this is result what I want.
}
],
}
]
This my code :
public function index(Request $request)
{
try {
$query = $this->dashboard->with('rolesDashboard','userDashboard')
->orderBy('id')
->get();
$data=[];
foreach ($query as $key) {
$data_chart = DB::select($key->function_name); //call store procedure from SQL Server
$color = array(
"0xFF000000" ,
"0xFF444444" ,
"0xFF888888" ,
"0xFFCCCCCC",
"0xFFFFFFFF",
"0xFFFF0000" ,
"0xFF00FF00" ,
); // this is array color
for ($i=0; $i < count($data_chart) ; $i++) {
$set = $color[$i]; //Get data array color
}
foreach($data_chart as $row){
$row->color = $set;
}
$data[] = [
'title' => $key->title,
'function_name' => $key->function_name,
'created_at' => $key->created_at,
'updated_at' => $key->updated_at,
'data_chart' => $data_chart, //return data_chart and color
];
}
return response()->default(200, trans('messages.success.get-data'),$data);
} catch (Exception $e) {
return response()->default(400, $e->getMessage());
}
}
$set is array, cannot be assigned as a string. My advice is changing below code:
for ($i=0; $i < count($data_chart) ; $i++) {
$set = $color[$i]; //Get data array color
}
foreach($data_chart as $row){
$row->color = $set;
}
to
$i=0;
foreach($data_chart as $row){
$row->color = $color[$i];
$i++;
}
but if your $data_chart count is more than $color count it will return error, for better handling use code below:
$i=0;
foreach($data_chart as $row){
if(isset($color[$i])){
$row->color = $color[$i];
$i++; }
else{
$i=0;
}
}
Related
This question already has answers here:
How to group subarrays by a column value?
(20 answers)
PHP - Group Array by its Sub Array Value (Indexed Array)
(1 answer)
Closed 6 months ago.
i have this array in php json.
i have made it to sort array by first Characther.
but now i'm stuck on how to merge the data under the same title.
my response now is.
[
{
"title": "A",
"data": {
"id": "317",
"name": "Aesethetica"
}
},
{
"title": "A",
"data": {
"id": "318",
"name": "Astonos"
}
},
{
"title": "B",
"data": {
"id": "320",
"name": "Bourjois"
}
},
{
"title": "B",
"data": {
"id": "321",
"name": "Bioderma"
}
}
]
i need to merge all data under each same title.
something like this:
[
{
"title": "A",
"data": [
{
"id": "317",
"name": "Aesethetica"
},
{
"id": "318",
"name": "Astonos"
}
]
},
{
"title": "B",
"data": [
{
"id": "320",
"name": "Bourjois"
},
{
"id": "321",
"name": "Bioderma"
}
]
}
]
kindly help.
Thanks
i got this now:
i made this update.. but still not the needed result.
this is my php code...
$result = [];
foreach ($data as $item) {
$firstLetter = substr($item['name'], 0, 1);
$result[] = [
'title' => $firstLetter = ctype_alnum($firstLetter) ? $firstLetter : '#',
'data' => $item
];
}
foreach ($result as $key => $item) {
$arr[$item['title']][$key] = $item;
}
and this is the result.
{
"A": [
{
"title": "A",
"data": {
"brand_id": "312",
"brand_name": "Adidsa"
}
},
{
"title": "A",
"data": {
"id": "314",
"name": "Adio"
}
},
still can't find make the needed response..
This is not perfomance optimized, but shows a simple solution.
Collect all data grouped by title, then reformat the array to your expected result.
$array = json_decode($json, true);
$collect = [];
foreach($array as $item) {
$collect[$item['title']][] = $item['data'];
}
ksort($collect);
$titles = [];
foreach($collect as $title => $data) {
$names = array_column($data, 'name');
array_multisort($names, SORT_ASC, SORT_STRING, $data);
$titles[] = ['title' => $title, 'data' => $data];
}
echo json_encode($titles, JSON_PRETTY_PRINT); results in
[
{
"title": "A",
"data": [
{
"id": "317",
"name": "Aesethetica"
},
{
"id": "318",
"name": "Astonos"
}
]
},
{
"title": "B",
"data": [
{
"id": "321",
"name": "Bioderma"
},
{
"id": "320",
"name": "Bourjois"
}
]
}
]
I have question, is it possible not to duplicate the array object by looping on it? Right now I used laravel as my backend
I have here my response which is the exchange object duplicate itself.
[
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "001",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
},
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "002",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
},
]
Now my goal is to push the exchange without duplication:
[
{
"exchange": {
"id": 1,
"branch": "BB1",
"old_check_no": "0001",
"cash": "250000",
"bank_deposit": "1000000",
"offset": "250000",
"amount": "10000",
"over_under": null,
"checkDate": "2021-09-11",
"remarks": "1",
"date_closed": "2021-09-11"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "001",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
},
"exchange_list": {
"exchange_id": 1,
"new_check_no": "002",
"new_check_bank": "bank",
"new_check_branch": "Lagros"
}
}
]
Here is what my foreach loop like and how i push the array object.
$myArray = [];
foreach($exchange_check as $primary_array) {
foreach($exchange_lists as $second_array) {
if($second_array->exchange_id == $primary_array->id) {
array_push($myArray, (object)[
'exchange' => $primary_array,
'exchange_list' => $second_array,
]);
}
}
}
Thanks
You should add exchange data to array only once in first loop:
$myArray = [];
foreach($exchange_check as $primary_array) {
$idx = array_push($myArray, ['exchange' => $primary_array]);
foreach($exchange_lists as $second_array) {
if($second_array->exchange_id == $primary_array->id) {
//array_push() returns the new number of elements in the array,
//to get currently added array element we should subtract 1 from this number
$myArray[$idx-1]['exchange_list'][] = $second_array;
}
}
}
And in second loop add only exchange_list data to array.
Supposed I have a query that gets the image from a certain tweet
[
{
"pic": "/upload/15680712995mb.jpg",
"tweet_id": "48"
},
{
"pic": "/upload/1568071299test.PNG",
"tweet_id": "48"
},
{
"pic": "/upload/1568015310test.PNG",
"tweet_id": "47"
}
]
And I have a result also from a query that gets all of the tweet
[
{
"id": "48",
"tweet": "test",
},
{
"id": "47",
"tweet": "test tweet",
},
{
"id": "45",
"tweet": "test tweet 3",
}
]
How can I format the result like this (Just like on laravel)
[
{
"id": "48",
"tweet": "test",
"pics": [
[
"/upload/15680712995mb.jpg"
],
[
"/upload/1568071299test.PNG"
],
]
},
{
"id": "47",
"tweet": "test tweet",
"pics" : [
[
"/upload/1568015310test.PNG"
]
]
},
{
"id": "45",
"tweet": "test tweet 3",
"pics" : []
}
]
And this is my simplified code
public function getTweets()
{
$pics = $this->model->getPics();
$aTweets = $this->model->getTweets();
$map = [];
$props = [];
foreach ($aTweets as $sTweet) {
$map['id'] = $sTweet['id'];
$map['tweet'] = $sTweet['tweet'];
foreach ($pics as $pic) {
if ($pic['id'] === $sTweet['tweet_id']) {
$map['pics'] = [$pic['pic']];
}
}
$props[] = $map;
}
return $props;
}
but it just gives me the following output
{
"id": "48",
"tweet": "test",
"pics": [
"/upload/1568015310test.PNG"
]
},
{
"id": "47",
"tweet": "test tweet",
"pics": [
"/upload/1568015310test.PNG"
]
},
Any idea how can I format the result. thanks in advance.?
I'm not sure what's troubling you but in order to add multiple values inside, just put another nesting like what I've eluded in the comments section:
$map['pics'][] = $pic['pic'];
// ^
So to complete the answer:
$map = [];
$props = [];
foreach ($aTweets as $sTweet) {
$map['id'] = $sTweet['id'];
$map['tweet'] = $sTweet['tweet'];
$map['pics'] = []; // initialize
foreach ($pics as $pic) {
if ($pic['tweet_id'] === $sTweet['id']) {
$map['pics'][] = [$pic['pic']];
}
}
$props[] = $map;
}
This essentially creates another dimension for pics index as an array and continually pushing, provided they have the same ID.
Sidenote: tweet_id is to pics and id is to aTweets. Your's have the other way around.
I have problem with this script...
My script has return this:
{
"categories": {
"cid": "1",
"name": "Pierwsza pomoc"
}
}{
"categories": {
"cid": "2",
"name": "Poradniki"
}
}{
"categories": {
"cid": "3",
"name": "Klany"
}
}{
"categories": {
"cid": "4",
"name": "Eventy, imprezy"
}
}{
"categories": {
"cid": "5",
"name": "Rozm\u00f3wki"
}
}{
"categories": {
"cid": "6",
"name": "Quest, solucje"
}
}{
"categories": {
"cid": "7",
"name": "Off topic"
}
}
But i want to this
[
'categories': {
'cid': 1,
'name': 'test',
'cid': 2,
'name': 'asdsad',
'cid': 3,
'name': 'asdasd'
}
]
Code used to create the data is
if($query->rowCount() > 0){
foreach($query as $row){
$Forum->writeJSON(array('categories' => array( 'cid' => $row['id'], 'name' => $row['name'] )));
}
}
class Forum {
public function writeJSON($array){
echo json_encode($array, JSON_PRETTY_PRINT);
}
}
$Forum = new Forum;
Well, this structure is not possible. You cannot store two or more elements with exactly same key in same object. However maybe you simply want this output:
[ 'categories' : { 1: {category_id:1, name:'test'}, 2: {category_id:2, name:'test'} } ]
It is simple, for example, you can use something like this to form that array:
<?php
//fetch data into categories variable
$output = array();
$output['categories'] = array();
foreach ($category as $category){
$output['categories'][] = array('category_id' => $category['id'], 'name' => $category['name']);
}
$output = json_encode($output);
?>
PS: Please use the correct variable names in your code, this is just an example using fictitious variable names
You need to change your foreach loop code
if($query->rowCount() > 0){
foreach($query as $row){
$cat_array[$row['id']] = array('cid'=>$row['id'],'name'=>$row['name']);
}
$json_array[] = array('categories'=>$cat_array);
$Forum->writeJSON($json_array);
}
For 2 days, I'm trying to extract informations from a multidimensional array and I think I'm stuck after trying a lot of things
Here is my json
{
"profile": [
{
"id": "123456",
"hostId": null,
"description": [
{
"id": "name",
"value": "foo"
},
{
"id": "name2",
"value": "foo2"
},
{
"id": "bio",
"value": "heyyyy"
},
{
"id": "location",
"value": "somewhere"
}
],
"ishere": true
}
]
}
I want to manipulate it to have this
{
"id": "123456",
"host": null,
"name": "foo",
"name2": "foo2",
"bio": "heyyyy",
"location": "somewhere",
"ishere": true
}
with this (after a json_decode)
foreach ($array->profileUsers[0]->settings as $item) {
$out2[$item->id] = $item->value;
}
I only have
{
"name": "foo",
"name2": "foo2",
"bio": "heyyyy",
"location": "somewhere"
}
Thank you
This should do the trick:
$obj = json_decode($your_json);
$obj = $obj->profile[0];
foreach($obj->description as $d)
$obj->{$d->id} = $d->value;
unset($obj->description);
$data = json_decode($your_json, true);
$new_array = [];
foreach($data['profile'] as $key=>$item) {
if(is_array($item)) {
$new_array[$item['id']] = $item['value'];
}
else {
$new_array[$key] = $item;
}
}
Hardcoded this, hope it will help.