質問

After fetching a result from the database, and preparing the array for the JSON enconde, I face a dilemma on how to reference the array 'data' inside the main array.

The "[0]" by far is an error of my logic...

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

The vardump show as follow:

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

But I want to add the last item with same id/name like this:

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"
      }
    }
  }
}
役に立ちましたか?

解決

The most natural way would be to change your data structure a bit, so that the series array is indexed by the row ID instead of an arbitrary running index. The would allow you to rewrite your loop to (using mysqli syntax as an example):

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

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

which will give you a data structure like:

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

If you need the data in the exact format shown in your post, you can of course loop over this array with foreach to transform it, e.g.:

$rows = array();
foreach ( $series as $id => $record ) {
    $record['id'] = $id;
    $rows['series'][] = $record;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top