0
[{
"productname" : "product 1",
"label" :["used license", "unused license"],
"value" : [16,15]
},
{
"productname" : "product 2",
"label" :["used license", "unused license"],
"value" : [16,15]
}]

I am trying to create the above format from laravel code.But there were no success so far. In the above code label is the names of two columns and value are the values of two columns.

My code so far is below

 $licenses_count = products::select('product_name AS 
 productname','total_license', 'license_remaining')
        ->get();
        return $licenses_count;

my code output

[{
 "productname" : "product 1",
 "total_licenses" :5,
 "remaining_licenses" : 11,
 },
 {
 "productname" : "product 2",
 "total_licenses" :16,
 "remaining_licenses" : 15,
}]

Any help would be appreciated.

2 Answers 2

1

I changed the code as below which is working as in the required format.

$result = array();
foreach($licenses_count as $row){
            foreach($row as $k=>$v){
                $product = array();
               if($v=="productname"){
                  $product['productname'] = $row->productname;
               }
               if($v=="total_license"){
                  //return $row;
                  $product['label'][] = 'used license';
                  $product['value'][] = $row->total_license;
               }
               if($v=="license_remaining"){
                  $product['label'][] = 'unused license';
                  $product['value'][] = $row->license_remaining;
               }
            }
            $result[] = $product;
        }
        return $result;
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

$licenses_count = products::select('product_name AS 
productname','total_license', 'license_remaining')
    ->get();

$result = array();
foreach($licenses_count as $row){
    $product = array();
    foreach($row as $k => $v){
       if($k=="productname"){
          $product['productname'] = $v;
       }
       if($k=="total_licenses"){
          $product['label'][] = 'used license';
          $product['value'][] = $v;
       }
       if($k=="remaining_licenses"){
          $product['label'][] = 'unused license';
          $product['value'][] = $v;
       }
    }
    $result[] = $product;
}

return $result;

2 Comments

Thanks, When i tried your code, it was giving empty array. But i modified the code as below. which is working as expected.
Oh yeah you are right. Must access row as obejct to get the value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.