2017-11-27 8 views
-4

PHPでエンコードしたJSONオブジェクトを繰り返し処理しようとしましたが、pngファイルを含むディレクトリをループしています。 私はgetLayersObjectのJSONを繰り返し処理することはできません。 次のコードを試したが、うまくいかなかった。 提案がありますか?JSONオブジェクトを反復しようとしています

<?php 

    $dir = "layers"; 
    $layers = array(); 
    if (is_dir($dir)) { 
    if ($dh = opendir($dir)) { 
     while (($file = readdir($dh)) !== false) { 
     if ($file != '.' && $file != '..') { 
      array_push($layers, $file); 
     } 
    } 
    closedir($dh); 
    } 
} 

echo json_encode(array('phone' => $layers), JSON_FORCE_OBJECT); 
?> 

はJavaScript

var Layers = (function() { 
var layers = []; 
var mobileLayer = ''; 
var initialisering = function(){ 
    var xmlhttp = new XMLHttpRequest(); 
    xmlhttp.onreadystatechange = function() { 
     if (this.readyState == 4 && this.status == 200) { 
      var myObj = JSON.parse(xmlhttp.responseText); 
      layers.push(myObj); 
     } 
    }; 
    xmlhttp.open("GET", "http://localhost/layers/get_layers.php", true); 
    xmlhttp.send(); 
    getLayersObject(); 

}; 

var getLayersObject = function(){ 
    mobileLayer = document.getElementsByClassName('layer'); 
    Object.keys(layers.phone).forEach(function(key,index) { 
     console.log(key, layers.phone[index]); 
    }); 
} 

return { 
    initialisering: initialisering 
    }; 
})(); 

window.addEventListener("load", Layers.initialisering()); 

JSON結果

{ 
    "phone": { 
    "0": "11.png", 
    "1": "12.png", 
    "2": "14.png", 
    "3": "15.png", 
    "4": "4.png", 
    "5": "7.png", 
    "6": "9.png", 
    "7": "front_kamera.png" 
    } 
} 
+3

あなたが試したいくつかのコードを持っていますか? – kevin628

+0

'json'タグの使用法の説明を読んだことがありますか? – trincot

+1

これは単なるオブジェクトです。 JSONではありません。ネストしたオブジェクトではなく配列を電話機にすると、何も失うことなく簡単な配列の繰り返しを使用できるようになります(現在、オブジェクトのキーは配列であり、数値と連続です)。 – James

答えて

0

これは普通のオブジェクトです。 Object.keysを使用して.forEach()でそれを列挙してください。

var obj = { 
 
"phone": { 
 
    "0": "11.png", 
 
    "1": "12.png", 
 
    "2": "14.png", 
 
    "3": "15.png", 
 
    "4": "4.png", 
 
    "5": "7.png", 
 
    "6": "9.png", 
 
    "7": "front_kamera.png" 
 
    } 
 
}; 
 

 
Object.keys(obj.phone).forEach(function(key,index) { 
 
    // key: the name of the object key 
 
    // index: the ordinal position of the key within the object 
 
    console.log(key, obj.phone[index]); 
 
});

関連する問題