简体   繁体   中英

i want foreach inside an array

i want to add include foreach inside an array, how can i do that

<?php

    foreach($query as $row)
    {
        $cat=$row->categoery:
        $expenses=$row->expenses;

    }

how i can take this foreach loop inside this $jsondata?

i did like this

foreach($query as $row)
{
    $cat=$row->categoery:
    $expenses=$row->expenses;

    $jsonData = array
    (
        array("$cat", $expenses),
    );
}

You will just reinitialised $jsonData by doing as you did for each iteration.

$jsonData = array();

foreach($query as $row){
   $cat=$row->categoery:
   $expenses=$row->expenses;

   $jsonData[$cat] = $expenses;
}

// in Your current loop value of array $jsonData is override for new value, so you always get last row Value in your $jsonData

foreach($query as $row)
{
    $cat=$row->categoery:
    $expenses=$row->expenses;

    $jsonData = array
    (
        array("$cat", $expenses), // This Syntax of array is use to define Array  
    );
}

Here The Correction

  $jsonData = array(); // Here we define array 
    foreach($query as $row)  {
            $jsonData[trim($row->categoery)] = $row->expenses; //assign 
            $jsonData[$i] = $row->expenses; //to get expenses 
            $jsonData[$i] = $row->categoery; //to get  categoery
               $i++;
        }
    print_($jsonData) //here your array

 $arrData = array(); foreach($query as $row) { $cat=$row->categoery: $expenses=$row->expenses; $arrData[$cat] = $expenses; } echo json_encode($arrData); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM