How To Access Values In Associative Array Using PHP

前端 未结 3 1459
予麋鹿
予麋鹿 2021-01-25 10:02

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 ( [N         


        
相关标签:
3条回答
  • 2021-01-25 10:41

    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.

    0 讨论(0)
  • 2021-01-25 10:56
    foreach ($result as $item) {
      foreach ($item['Attributes'] as $keyvalue) {
        if ($keyvalue['Name'] == 'test_id' || $keyvalue['Name'] == 'test_name') {
          echo $keyvalue['Value'];
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-25 11:02

    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
    }
    
    0 讨论(0)
提交回复
热议问题