Hello. Please help me understand, I have an array in php :

<?php $credit=array( array('Номер 1','10','03'), array('Номер N','N','N'), array('Номер 10','6','12') ); ?> var credit_m_m = <?php echo json_encode($credit_m_m);?>; 

I need to convert the php array to js , as shown in the example below:

 var options = { manualInput: false, order:[{ model: 1, quanity: 10, date: 03 }, { model: N, quanity: N, date: N }, { model: 10, quanity: 6, date: 12 }] } 

How to convert an array from php , js array "order"?

  • In your php array 3 values ​​in the array, in the js array - 4, something already does not converge. - Yaroslav Molchan
  • Sorry, did not remove the extra value. - Maxim M
  • if you do this, print_r(json_decode(result_json, true)); - see which array structure you need. I think nothing complicated is needed - splash58
  • Do not forget about JSON_HEX_TAG otherwise JSON_HEX_TAG will suffer from XSS to fight - tutankhamun

2 answers 2

The problem is that there are no keys in your PHP array, but if you assume that the values ​​go in the same order as in the JS array, you can convert it like this:

 // Ваш исходный массив. $credit=[ ['Номер 1','10','03'], ['Номер N','N','N'], ['Номер 10','6','12'] ]; // Готовим массив с нужным форматом. $response = [ 'manualInput' => false, 'order' => [] ]; // Конвертируем массив в тот что хотим увидеть в JS. foreach ($credit as $item) { $response['order'][] = [ 'model' => filter_var($item[0], FILTER_SANITIZE_NUMBER_INT), 'quanity' => $item[1], 'date' => $item[2] ]; } ?> var credit_m_m = <?php echo json_encode($response); ?>; 

    something like that? If your N is test data and the values ​​are actually integer, then add a la (int)$q

     $data = array_map(function($v){ list($m, $q, $d) = $v; return [ 'model' => str_replace("Номер ", "", $m), 'quantity' => $q, // (int)$q 'date' => $d, // (int)$d ]; }, $credit); echo json_encode($data, JSON_UNESCAPED_UNICODE); 

    alternative way to write the callback function body

     list($model, $quantity, $date) = $v; $model = str_replace("Номер ", "", $model); return compact(['model', 'quantity', 'date']);