简体   繁体   English

如何使用PHP访问关联数组中的值

[英]How To Access Values In Associative Array Using PHP

I have an array which is the result of a select query using Amazon SimpleDb. 我有一个数组,它是使用Amazon SimpleDb的select查询的结果。

Here is sample data when I print_r($result); 这是我print_r($ result)时的示例数据;

Array ( [0] => Array ( [Name] => 5140ede647e74
                       [Attributes] => Array (
                            [0] => Array ( [Name] => test_id [Value] => 5140ede647e74 )
                            [1] => Array ( [Name] => test_name [Value] => test1 )
                            [2] => Array ( [Name] => last_update [Value] => 1363209702 )
                            [3] => Array ( [Name] => created [Value] => 1363209702 ) ) ) ) 

If I want to extract the test_id and the test_name, how can I do it? 如果我想提取test_id和test_name,我该怎么办? I am currently doing the following 我目前正在做以下事情

<?php foreach ($result as $item) {
    echo $item['Attributes'][0]['Value']; 
    echo $item['Attributes'][1]['Value'];
} ?>

But I want to do it by referencing "test_id" and "test_name" because when I delete the domain where the data resides and re-enter the data, the order of each attribute can change so I can't trust that $item['Attributes'][0]['Value'] will always be the test_id 但是我想通过引用“test_id”和“test_name”来实现它,因为当我删除数据所在的域并重新输入数据时,每个属性的顺序都可以改变,所以我不能相信那个$ item ['属性'] [0] ['值']将始终是test_id

Thanks! 谢谢!

You need to recast the Array. 你需要重铸数组。

$newArray = array();
foreach ($result as $key=>$row)
{        
    foreach ($row['Attributes'] AS $row2)
    {
         $newArray[$key][$row2['Name']] = $row2['Value'];
    }       
}

EDIT: It depends on what you need to do - this is my preferred method if I plan on doing a lot of work with a resultset - I only need to iterate through the set once and then it's in a format where the data can be accessed quickly. 编辑:这取决于你需要做什么 - 如果我打算用结果集做很多工作,这是我首选的方法 - 我只需要遍历集合一次然后它就是一种可以访问数据的格式很快。

The following will run trough the last part of your array by reference. 以下内容将通过引用运行到数组的最后一部分。 Therefore edits that you make are reflected in the $result array. 因此,您所做的编辑会反映在$result数组中。

foreach ($result[0]['Attributes'] as &$item) {
    if ($item['Name'] == 'test_id') // do something
}
foreach ($result as $item) {
  foreach ($item['Attributes'] as $keyvalue) {
    if ($keyvalue['Name'] == 'test_id' || $keyvalue['Name'] == 'test_name') {
      echo $keyvalue['Value'];
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM