使用javascript或php从json数组中获取值

时间:2014-12-09 10:54:27

标签: javascript php json

这是我的代码:

var newval =[{"new_id":"1","new_no":"1","total":"N.A"},{"new_id":"2","new_no":"3","total":"4"},{"new_id":"2","new_no":"4","total":"5"}];

从这个json值如何使用javascript或php获取基于new_no值的详细信息。

  function passfun(new_no)
  {
    alert(newval[0].plot_no);
  }

我试过这样但是它的工作基于json数组值我得不到基于new_no的确切值

1 个答案:

答案 0 :(得分:0)

您有一个JSON格式的对象数组。在PHP中,您可以使用以下代码:

PHP:

<?php
$json = '[{"new_id":"1","new_no":"1","total":"N.A"},{"new_id":"2","new_no":"3","total":"4"},{"new_id":"2","new_no":"4","total":"5"}]';

$data = json_decode($json);

function get_prop($object, $name)
{
    return $object->{$name};

}


print get_prop($data[0], 'new_no')."\n";
print get_prop($data[0], 'new_id')."\n";

JavaScript的:

var newval =[{"new_id":"1","new_no":"1","total":"N.A"},
             {"new_id":"2","new_no":"3","total":"4"},
             {"new_id":"2","new_no":"4","total":"5"}];

function get_prop(obj, name)
{
    return obj[name];
}

alert(get_prop(newval[0], 'new_no'));