繁体   English   中英

PHP中数组内的关联数组

[英]Associative array inside array in PHP

从数据库中获取结果并为JSON enconde准备数组之后,我面临着如何在主数组中引用数组“数据”的难题。

到目前为止,“ [0]”是我的逻辑错误...

while ($row =$result->fetch()) {
    $name     = $row['country'];
    $id       = $row['id']
    $username = $row['username'];
    $subtotal = $row['subtotal'];

    if ( /* If $id exist in array row['series']}*/ ) {

        ///?????/////
        /// Add array to 'DATA'
        ////?????////

        $rows['series']["$id"]["$name"]['data'][]=array("$username", $subtotal);
    }
    else {
        $rows['series'][]= array('id' => "$id", 'name' => "$name", 'data' => array("$username", $subtotal));
    }

vardump显示如下:

array(1) {
  ["series"]=>
  array(2) {
    [0]=>
    array(3) {
      ["id"]=>
      string(7) "hn"
      ["name"]=>
      string(8) "HN"
      ["data"]=>
      array(2) {
        [0]=>
        string(17) "GK_5"
        [1]=>
        string(5) "86040"
      }
    }
    [1]=>
    array(3) {
      ["id"]=>
      string(7) "hn"
      ["name"]=>
      string(8) "HN"
      ["data"]=>
      array(2) {
        [0]=>
        string(17) "GK_8"
        [1]=>
        string(5) "20358"
      }
    }
  }
}

但我想添加具有相同ID /名称的最后一项,如下所示:

array(1) {
  ["series"]=>
  array(2) {
    [0]=>
    array(3) {
      ["id"]=>
      string(7) "hn"
      ["name"]=>
      string(8) "HN"
      ["data"]=>
      array(2) {
        [0]=>
        string(17) "GK_5"
        [1]=>
        string(5) "86040"
      }
      array(2) {
        [0]=>
        string(17) "GK_8"
        [1]=>
        string(5) "20358"
      }
    }
  }
}

最自然的方法是稍微更改数据结构,以便通过行ID而不是任意运行索引来索引series数组。 这将允许您将循环重写为(以mysqli语法为例):

$stmt->bind_result($id, $country, $username, $subtotal);

$series = array();
while ( $stmt->fetch() ) {
     $series[$id]['country'] = $country;
     $series[$id]['data'][] = array(
         'username' => $username,
         'subtotal' => $subtotal,
     );
}

将为您提供如下数据结构:

$series = array(
    'hn' => array(
        'country' => 'HN',
        'data' => array(
            0 => array(
                'username' => 'GK_5',
                'subtotal' => 86040
            ),
            1 => array(
                'username' => 'GK_8',
                'subtotal' => 20358
            ),
            // ...
        )
    ),
    // ...
);

如果您需要与帖子中显示的格式完全相同的数据,则当然可以使用foreach此数组以对其进行转换,例如:

$rows = array();
foreach ( $series as $id => $record ) {
    $record['id'] = $id;
    $rows['series'][] = $record;
}

暂无
暂无

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

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