如何加载关联数组

时间:2014-02-04 06:40:46

标签: php json

预期json

[
{
 "oV":"myfirstvalue",
 "oT":"myfirsttext"
 },
 {
 "oV":"mysecondvalue",
 "oT":"mysecondtext"
 }
]

我试图通过从数组myfirsttext[]myfirstvalue[]加载数据来创建关联数组,而不是从数组中获取这些数据。我尝试了以下,但失败了; expectedJSON高于

for($d=0;$d<4;$d++){
  $data = array(
   (object)array(
     'oV' => myfirstvalue[$d],
     'oT' => myfirsttext[$d],
    ),
  );
}

请帮助

3 个答案:

答案 0 :(得分:4)

如果myfirsttextmyfirsttext是数组,请执行以下操作:$myFirstValue$myFirsttext

你也在覆盖每个循环$data

$data = array();
for ($d = 0; $d < 4; $d++) {
    $data[] = array('oV' = > $myfirstvalue[$d], 'oT' = > $myfirsttext[$d]);
}

<强>更新

然后在javascript中获取它,请使用json_encode

<script>
var data = <?php echo json_encode($data) ?>;
jQuery.each(data, function(index, value) {
    console.log(value.oV, value.oT);
});
</script>

或者使用ajax:

<script>
jQuery.getJSON('/somefile.php', function(data) {    
    jQuery.each(data, function(index, value) {
        console.log(value.oV, value.oT);
    });
});
</script>

somefile.php 的位置如下:

...
$data = array();
for ($d = 0; $d < 4; $d++) {
    $data[] = array('oV' = > $myfirstvalue[$d], 'oT' = > $myfirsttext[$d]);
}
header('Content-Type: application/json');
echo json_encode($data);

答案 1 :(得分:0)

你继续覆盖$data。试试这个:

$data = array();
for($d=0;$d<4;$d++){
  $data[] = array(
     'oV' => $myfirstvalue[$d],
     'oT' => $myfirsttext[$d],
  );
}

答案 2 :(得分:-1)

只需将json字符串转换为stdObject或数组。

    $json = '[
          {
        "oV":"myfirstvalue",
        "oT":"myfirsttext"
        },
        {
        "oV":"mysecondvalue",
        "oT":"mysecondtext"
        }
        ]';

       //jsonArray: 
       $array = json_decode($json, true);

        //stdObject
        $json_stdObj = json_decode($json);
        echo "<pre>";print_r($json_stdObj );exit;

//输出[stdClass对象]

   Array
    (
     [0] => stdClass Object
       (
        [oV] => myfirstvalue
        [oT] => myfirsttext
       )

     [1] => stdClass Object
       (
        [oV] => mysecondvalue
        [oT] => mysecondtext
       )
    )