How To Access Values In Associative Array Using PHP

假如想象 提交于 2019-12-02 10:57:51

问题


I have an array which is the result of a select query using Amazon SimpleDb.

Here is sample data when I 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? 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

Thanks!


回答1:


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



回答2:


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.




回答3:


The following will run trough the last part of your array by reference. Therefore edits that you make are reflected in the $result array.

foreach ($result[0]['Attributes'] as &$item) {
    if ($item['Name'] == 'test_id') // do something
}


来源:https://stackoverflow.com/questions/15399903/how-to-access-values-in-associative-array-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!