anju
anju

Reputation: 99

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),
    );
}

Upvotes: 0

Views: 64

Answers (3)

Indra
Indra

Reputation: 78

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

	$arrData[$cat] = $expenses;
}

echo json_encode($arrData);

Upvotes: 0

Shailendra Sharma
Shailendra Sharma

Reputation: 6992

// 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

Upvotes: 0

Xlander
Xlander

Reputation: 1331

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;
}

Upvotes: 2

Related Questions