简体   繁体   English

我想要数组内的foreach

[英]i want foreach inside an array

i want to add include foreach inside an array, how can i do that 我想在数组中添加include foreach,我该怎么做

<?php

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

    }

how i can take this foreach loop inside this $jsondata? 我如何才能在此$jsondata?使用此foreach循环$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

$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 //在数组$jsonData当前循环值中,新值将被覆盖,因此,您始终会在$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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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