从阵列中提取我想要的东西?

时间:2013-02-15 16:31:49

标签: php yaml

我有一个yaml文件,我需要解析成一个数组,我完成了。现在这个阵列很大。我只想要几个价值观......

X1,Y1,X2,Y2,所有者,这就是我想要的。如果我可以让他们很好地吐出阵列,那对我来说意味着世界。 (所有者必须是与X1,y1,x2,y2值相关的所有者......

(它们都是相互关联的)阵列中有很多x1,y1,但它们都属于标题...等我不知道如何把它们全部搞定......

以下是数组吐出的内容......(由于文件大小限制而缩短) http://pastebin.com/PyH18mZv

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:2)

要解析YAML,您可以使用各种可用的PHP解析器。我使用Online YAML Parser解析你的YAML并输出JSON中的字符串。最后,可以通过解码JSON来访问所需的数组值。

* 请注意我剪短字符串只是为了示例目的 *

$arr='{
"Residences": {
"WorkArea": {"BlackList": {"Type": "BLACKLIST", "ItemList": []}, 
  "EnterMessage": "Welcome %player to %residence, owned by %owner.", 
  "Areas": {
    "main": {
      "Y1": 217, 
      "X1": -6301, 
      "X2": -6306, 
      "Y2": 205, 
      "Z1": 3001, 
      "Z2": 2981
    }
  }, 
  "Permissions": {"Owner": "cal9897","World": "VivaWorld"}
}, 
"caylyn55": {
  "BlackList": {
    "Type": "BLACKLIST", 
    "ItemList": []
  }, 
  "EnterMessage": "Welcome %player to %residence, owned by %owner.", 
  "StoredMoney": 0, 
  "IgnoreList": {
    "Type": "IGNORELIST", 
    "ItemList": []
  }, 
  "LeaveMessage": "Now leaving %residence.", 
  "Subzones": {}, 
  "Areas": {
    "main": {
      "Y1": 67, 
      "X1": 1220, 
      "X2": 1210, 
      "Y2": 64, 
      "Z1": 369, 
      "Z2": 360
    }
  }, 
  "Permissions": {
    "Owner": "caylyn55",
    "PlayerFlags": {}, 
    "GroupFlags": {}, 
    "World": "VivaWorld"
  }
}
}, 
 "Version": 1, 
 "Seed": 1337068141
  }';

解码JSON

$a= json_decode($arr,true);

第一个区域值通过

$a['Residences']['WorkArea']['Areas']['main']['Y1'];

和第二区域值

$a['Residences']['caylyn55']['Areas']['main']['Y1'];  

if ['WorkArea']和['caylyn55']动态可以使用此代码

$b=array_values($a);
foreach($b as $values)
{
if(is_array($values)) {

    foreach(array_keys($values) as $c){

     echo  $a['Residences'][$c]['Areas']['main']['Y1'];

        }

    }

}

答案 1 :(得分:1)

您只需要添加对您要输出的数据的完整参考。

示例:echo $data['Residences']['WorkArea']['Permissions']['Owner'];

答案 2 :(得分:0)

像这样的东西

$extracted = array_map(function ($residence) {
    $r = $residence['Areas']['main'];
    $r['owner'] = $residence['Permissions']['Owner'];
    return $r;
}, $data['Residences']);