将数据插入到数组php pdo中

时间:2014-03-23 19:59:28

标签: php mysql arrays json

我有这段代码:

$rows = array();

      $table = array();
      foreach($kol as $r) {
          $temp = array();
          // the following line will be used to slice the Pie chart
          $m = array('label' => (string) $r['naziv'], 'type' => 'string'); 
        $rows[] = ($m);
        }


    $table['cols'] =  $rows;

我得到了这个json:

{"cols":[{"label":"Pera Peric","type":"string"},{"label":"IMT 510-td","type":"string"},{"label":"Laza Lazic","type":"string"}

如何将$ m数组上的数据放到位置0以获得这样的json:

{"cols":[{"label":"Datum,"type":"Date"},{"label":"Pera Peric","type":"string"},{"label":"IMT 510-td","type":"string"},{"label":"Laza Lazic","type":"string"}

所以在这里我只想添加这些数据:{"label":"Datum,"type":"Date"} to array ...

2 个答案:

答案 0 :(得分:2)

只需在开始循环之前添加它(我清理了一下):

$rows = array();
$table = array();

$rows[] = array('label' => 'Datum', 'type' => 'Date')

foreach ($kol as $r) {
    $rows[] = array('label' => (string) $r['naziv'], 'type' => 'string');
}

$table['cols'] =  $rows;

答案 1 :(得分:1)

array_unshift()

<?php

// your json
$json = '{"cols":[{"label":"Pera Peric","type":"string"},{"label":"IMT 510-td","type":"string"},{"label":"Laza Lazic","type":"string"}]}';

// json array to php array using json_decode()
$json_decode = json_decode($json, true);

// your $m php array
$m = array(
  'label' => 'Datum',
  'type' => 'Date'
);

// add you $m to position 0 in index 'cols'
array_unshift($json_decode['cols'], $m);

完成!

array(1) {
  ["cols"]=>
  array(4) {
    [0]=>
    array(2) {
      ["label"]=>
      string(5) "Datum"
      ["type"]=>
      string(4) "Date"
    }
    [1]=>
    array(2) {
      ["label"]=>
      string(10) "Pera Peric"
      ["type"]=>
      string(6) "string"
    }
    [2]=>
    array(2) {
      ["label"]=>
      string(10) "IMT 510-td"
      ["type"]=>
      string(6) "string"
    }
    [3]=>
    array(2) {
      ["label"]=>
      string(10) "Laza Lazic"
      ["type"]=>
      string(6) "string"
    }
  }
}

回到json(如果你想)

$json = json_encode($json_decode);