0

I have this code:

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

and I get this json:

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

How I can put data on $m array to position 0 to get json like this:

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

so here I just want to add this data: {"label":"Datum,"type":"Date"} to array ...

2 Answers 2

2

Just add it before you start your loop (I cleaned a bit):

$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;
Sign up to request clarification or add additional context in comments.

Comments

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

Done!

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

Back to json (if you want)

$json = json_encode($json_decode);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.