簡體   English   中英

如何訪問數組/對象?

[英]How can I access an array/object?

我有以下數組,當我執行print_r(array_values($get_user)); ,我得到:

Array (
          [0] => 10499478683521864
          [1] => 07/22/1983
          [2] => email@saya.com
          [3] => Alan [4] => male
          [5] => Malmsteen
          [6] => https://www.facebook.com  app_scoped_user_id/1049213468352864/
          [7] => stdClass Object (
                   [id] => 102173722491792
                   [name] => Jakarta, Indonesia
          )
          [8] => id_ID
          [9] => El-nino
          [10] => Alan El-nino Malmsteen
          [11] => 7
          [12] => 2015-05-28T04:09:50+0000
          [13] => 1
        ) 

我嘗試按如下方式訪問數組:

echo $get_user[0];

但這向我展示了:

未定義 0

筆記:

我從Facebook SDK 4得到這個數組,所以我不知道原始數組結構。

例如,如何從陣列中訪問值email@saya.com

要訪問arrayobject您可以使用兩種不同的運算符。

數組

要訪問數組元素,您必須使用[]

echo $array[0];

在較舊的 PHP 版本上,還允許使用{}的替代語法:

echo $array{0};

聲明數組和訪問數組元素的區別

定義數組和訪問數組元素是兩件不同的事情。 所以不要把它們混在一起。

要定義數組,您可以使用array()或 PHP >=5.4 []並分配/設置數組/元素。 如上所述,當您使用[]訪問數組元素時,您將獲得與設置元素相反的數組元素的值。

//Declaring an array
$arrayA = array ( /*Some stuff in here*/ );
$arrayB = [ /*Some stuff in here*/ ]; //Only for PHP >=5.4

//Accessing an array element
echo $array[0];

訪問數組元素

要訪問數組中的特定元素,您可以使用[]{}任何表達式,然后計算為您要訪問的鍵:

$array[(Any expression)]

因此,請注意您用作鍵的表達式以及 PHP 如何解釋它:

echo $array[0];            //The key is an integer; It accesses the 0's element
echo $array["0"];          //The key is a string; It accesses the 0's element
echo $array["string"];     //The key is a string; It accesses the element with the key 'string'
echo $array[CONSTANT];     //The key is a constant and it gets replaced with the corresponding value
echo $array[cOnStAnT];     //The key is also a constant and not a string
echo $array[$anyVariable]  //The key is a variable and it gets replaced with the value which is in '$anyVariable'
echo $array[functionXY()]; //The key will be the return value of the function

訪問多維數組

如果彼此之間有多個數組,則只需一個多維數組。 要訪問子數組中的數組元素,您只需使用多個[]

echo $array["firstSubArray"]["SecondSubArray"]["ElementFromTheSecondSubArray"]
         // ├─────────────┘  ├──────────────┘  ├────────────────────────────┘
         // │                │                 └── 3rd Array dimension;
         // │                └──────────────────── 2d  Array dimension;
         // └───────────────────────────────────── 1st Array dimension;

對象

要訪問對象屬性,您必須使用->

echo $object->property;

如果你在另一個對象中有一個對象,你只需要使用 multiple ->來獲取你的對象屬性。

echo $objectA->objectB->property;

筆記:

  1. 如果您的屬性名稱無效,您也必須小心! 因此,要查看所有問題,您可能會遇到無效的屬性名稱,請參閱此問題/答案 如果您在屬性名稱的開頭有數字,則尤其如此

  2. 您只能從類外部訪問具有公共可見性的屬性。 否則(私有或受保護)您需要一個方法或反射,您可以使用它來獲取屬性的值。

數組和對象

現在,如果數組和對象相互混合,則只需查看現在是否訪問數組元素或對象屬性並使用相應的運算符。

//Object
echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property;
    //├────┘  ├───────────┘  ├───────────┘ ├──────────────────────┘   ├──────┘
    //│       │              │             │                          └── property ; 
    //│       │              │             └───────────────────────────── array element (object) ; Use -> To access the property 'property'
    //│       │              └─────────────────────────────────────────── array (property) ; Use [] To access the array element 'elementOneWithAnObject'
    //│       └────────────────────────────────────────────────────────── property (object) ; Use -> To access the property 'propertyArray'
    //└────────────────────────────────────────────────────────────────── object ; Use -> To access the property 'anotherObject'


//Array
echo $array["arrayElement"]["anotherElement"]->object->property["element"];
    //├───┘ ├────────────┘  ├──────────────┘   ├────┘  ├──────┘ ├───────┘
    //│     │               │                  │       │        └── array element ; 
    //│     │               │                  │       └─────────── property (array) ; Use [] To access the array element 'element'
    //│     │               │                  └─────────────────── property (object) ; Use -> To access the property 'property'
    //│     │               └────────────────────────────────────── array element (object) ; Use -> To access the property 'object'
    //│     └────────────────────────────────────────────────────── array element (array) ; Use [] To access the array element 'anotherElement'
    //└──────────────────────────────────────────────────────────── array ; Use [] To access the array element 'arrayElement'

我希望這能讓您大致了解如何訪問相互嵌套的數組和對象。

筆記:

  1. 如果它被稱為數組或對象取決於變量的最外層部分。 所以[new StdClass]是一個數組,即使它內部有(嵌套)對象並且$object->property = array(); 是一個對象,即使它內部有(嵌套)數組。

    如果您不確定是否有對象或數組,只需使用gettype()

  2. 如果有人使用與您不同的編碼風格,請不要讓自己感到困惑:

     //Both methods/styles work and access the same data echo $object->anotherObject->propertyArray["elementOneWithAnObject"]->property; echo $object-> anotherObject ->propertyArray ["elementOneWithAnObject"]-> property; //Both methods/styles work and access the same data echo $array["arrayElement"]["anotherElement"]->object->property["element"]; echo $array["arrayElement"] ["anotherElement"]-> object ->property["element"];

數組、對象和循環

如果您不只是想訪問單個元素,您可以遍歷嵌套數組/對象並遍歷特定維度的值。

為此,您只需要訪問要循環的維度,然后就可以循環該維度的所有值。

我們以一個數組為例,但它也可以是一個對象:

Array (
    [data] => Array (
            [0] => stdClass Object (
                    [propertyXY] => 1
                )    
            [1] => stdClass Object (
                    [propertyXY] => 2
                )   
            [2] => stdClass Object (
                    [propertyXY] => 3                   
               )    
        )
)

如果您遍歷第一個維度,您將獲得第一個維度的所有值:

foreach($array as $key => $value)

意味着在第一個維度中,您將只有 1 個帶有鍵( $keydata和值( $value )的元素:

Array (  //Key: array
    [0] => stdClass Object (
            [propertyXY] => 1
        )
    [1] => stdClass Object (
            [propertyXY] => 2
        )
    [2] => stdClass Object (
            [propertyXY] => 3
        )
)

如果您遍歷第二個維度,您將獲得第二個維度的所有值:

foreach($array["data"] as $key => $value)

意味着在第二個維度中,您將有 3 個元素,其中包含鍵( $key012和值( $value ):

stdClass Object (  //Key: 0
    [propertyXY] => 1
)
stdClass Object (  //Key: 1
    [propertyXY] => 2
)
stdClass Object (  //Key: 2
    [propertyXY] => 3
)

有了這個,你可以遍歷任何你想要的維度,無論它是數組還是對象。

分析var_dump() / print_r() / var_export()輸出

所有這 3 個調試函數都輸出相同的數據,只是采用另一種格式或帶有一些元數據(例如類型、大小)。 所以在這里我想展示您如何讀取這些函數的輸出以了解/了解如何從數組/對象訪問某些數據的方式。

輸入數組:

$array = [
    "key" => (object) [
        "property" => [1,2,3]
    ]
];

var_dump()輸出:

array(1) {
  ["key"]=>
  object(stdClass)#1 (1) {
    ["property"]=>
    array(3) {
      [0]=>
      int(1)
      [1]=>
      int(2)
      [2]=>
      int(3)
    }
  }
}

print_r()輸出:

Array
(
    [key] => stdClass Object
        (
            [property] => Array
                (
                    [0] => 1
                    [1] => 2
                    [2] => 3
                )

        )

)

var_export()輸出:

array (
  'key' => 
  (object) array(
     'property' => 
    array (
      0 => 1,
      1 => 2,
      2 => 3,
    ),
  ),
)

所以你可以看到所有的輸出都非常相似。 如果您現在想要訪問值 2,您可以從值本身開始,您想要訪問並找到“左上角”。

1. 我們首先看到,值 2 在一個鍵為 1 的數組中

// var_dump()
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)    // <-- value we want to access
  [2]=>
  int(3)
}

// print_r()
Array
(
    [0] => 1
    [1] => 2    // <-- value we want to access
    [2] => 3
)

// var_export()
array (
  0 => 1,
  1 => 2,    // <-- value we want to access
  2 => 3,
)

這意味着我們必須使用[]來訪問帶有[1]的值 2,因為該值具有鍵/索引 1。

2.接下來我們看到,該數組被分配給一個具有對象的name屬性的屬性

// var_dump()
object(stdClass)#1 (1) {
  ["property"]=>
  /* Array here */
}

// print_r()
stdClass Object
(
    [property] => /* Array here */
)

// var_export()
(object) array(
    'property' => 
  /* Array here */
),

這意味着我們必須使用->來訪問對象的屬性,例如->property

所以直到現在,我們知道我們必須使用->property[1]

3. 最后我們看到,最外層是一個數組

// var_dump()
array(1) {
  ["key"]=>
  /* Object & Array here */
}

// print_r()
Array
(
    [key] => stdClass Object
        /* Object & Array here */
)

// var_export()
array (
  'key' => 
  /* Object & Array here */
)

我們知道我們必須使用[]訪問數組元素,我們在這里看到我們必須使用["key"]來訪問該對象。 我們現在可以將所有這些部分放在一起並編寫:

echo $array["key"]->property[1];

輸出將是:

2

不要讓 PHP 欺騙你!

有一些事情你必須知道,這樣你就不會花幾個小時去尋找它們。

  1. “隱藏”字符

    有時,您的鍵中有字符,而您在瀏覽器中第一眼看不到這些字符。 然后你會問自己,為什么你不能訪問這個元素。 這些字符可以是:制表符( \\t )、換行符( \\n )、空格或 html 標簽(例如</p><b> )等。

    例如,如果您查看print_r()的輸出,您會看到:

     Array ( [key] => HERE )

    然后您嘗試使用以下方式訪問元素:

     echo $arr["key"];

    但是您收到通知:

    注意:未定義索引:鍵

    這是一個很好的跡象,表明必須有一些隱藏的字符,因為您無法訪問該元素,即使鍵看起來非常正確。

    這里的技巧是使用var_dump() + 查看您的源代碼! (替代: highlight_string(print_r($variable, TRUE));

    突然之間你可能會看到這樣的東西:

     array(1) { ["</b> key"]=> string(4) "HERE" }

    現在您將看到,您的密鑰中有一個 html 標簽 + 一個換行符,這是您一開始沒有看到的,因為print_r()和瀏覽器沒有顯示。

    所以現在如果你嘗試這樣做:

     echo $arr["</b>\\nkey"];

    您將獲得所需的輸出:

     HERE
  2. 如果您查看 XML,永遠不要相信print_r()var_dump()的輸出

    您可能將 XML 文件或字符串加載到對象中,例如

    <?xml version="1.0" encoding="UTF-8" ?> <rss> <item> <title attribute="xy" ab="xy">test</title> </item> </rss>

    現在如果你使用var_dump()print_r()你會看到:

     SimpleXMLElement Object ( [item] => SimpleXMLElement Object ( [title] => test ) )

    因此,如您所見,您看不到標題的屬性。 所以正如我所說,當你有一個 XML 對象時,永遠不要相信var_dump()print_r()的輸出。 始終使用asXML()來查看完整的 XML 文件/字符串。

    所以只需使用下面顯示的方法之一:

     echo $xml->asXML(); //And look into the source code highlight_string($xml->asXML()); header ("Content-Type:text/xml"); echo $xml->asXML();

    然后你會得到輸出:

     <?xml version="1.0" encoding="UTF-8"?> <rss> <item> <title attribute="xy" ab="xy">test</title> </item> </rss>

有關更多信息,請參閱:

一般(符號、錯誤)

屬性名稱問題

從問題我們看不到輸入數組的結構。 它可能是array ('id' => 10499478683521864, 'date' => '07/22/1983') 因此,當您詢問 $demo[0] 時,您使用的是 undefind 索引。

Array_values 丟失了鍵並返回帶有許多鍵的數組,使數組成為array(10499478683521864, '07/22/1983'...) 我們在問題中看到了這個結果。

因此,您可以通過相同的方式獲取數組項值

echo array_values($get_user)[0]; // 10499478683521864 

如果您的print_r($var)輸出是例如:

    Array ( [demo] => Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email@saya.com ) )

然后做$var['demo'][0]

如果print_r($var)的輸出是:

    Array ( [0] => 10499478683521864 [1] => 07/22/1983 [2] => email@saya.com )

然后做$var[0]

我編寫了一個小函數來訪問數組或對象中的屬性。 我經常使用它,發現它非常方便

/**
 * Access array or object values easily, with default fallback
 */
if( ! function_exists('element') )
{
  function element( &$array, $key, $default = NULL )
  {
    // Check array first
    if( is_array($array) )
    {
      return isset($array[$key]) ? $array[$key] : $default;
    }

    // Object props
    if( ! is_int($key) && is_object($array) )
    {
      return property_exists($array, $key) ? $array->{$key} : $default;
    }

    // Invalid type
    return NULL;
  }
}

在對響應數據調用array_values()之前,我將假設您的數據是關聯的,它看起來有點像這樣:

[
    'id' => 10499478683521864,
    'birthday' => '07/22/1983',
    'email' => 'email@saya.com',
    'first_name' => 'Alan',
    'gender' => 'male',
    'last_name' => 'Malmsteen',
    'link' => 'https://www.facebook.com/app_scoped_user_id/1049213468352864/',
    'location' => (object) [
        'id' => 102173722491792,
        'name' => 'Jakarta, Indonesia'
    ],
    'locale' => 'id_ID',
    'middle_name' => 'El-nino',
    'name' => 'Alan El-nino Malmsteen',
    'timezone' => 7,
    'updated_time' => '2015-05-28T04:09:50+0000',
    'verified' => 1
]

重新索引有效負載的鍵沒有任何好處。 如果您打算將數據轉換為數組,則可以通過使用json_decode($response, true)解碼 json 字符串來完成,否則json_decode($response)

如果您嘗試將$response作為 object 傳遞給array_values() ,則從 PHP8 將產生Fatal error: Uncaught TypeError: array_values(): Argument #1 ($array) must be of type array, stdClass given

在上面提供的數據結構中,有一個帶有關聯鍵的數組。

  • 要訪問特定的第一級元素,請使用帶引號的字符串鍵的“方括號”語法。
    • $response['id']訪問10499478683521864
    • $response['gender']訪問male
    • $response['location']訪問(object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
  • 要訪問嵌套在location (第二級)中的數據,需要“箭頭語法”,因為數據是 object。
    • $response['location']->id訪問102173722491792
    • $response['location']->name訪問Jakarta, Indonesia

在您的響應上調用array_values()后,該結構是一個索引數組,因此請使用方括號和不帶引號的整數。

  • $response[0]訪問10499478683521864
  • $response[4]訪問male
  • $response[7]訪問(object) ['id' => 102173722491792, 'name' => 'Jakarta, Indonesia']
  • $response[7]->id訪問102173722491792
  • $response[7]->name訪問Jakarta, Indonesia名稱

當您不確定您正在使用什么數據類型時,請使用var_export()var_dump()


對於 object 屬性(鍵)包含非法字符或緊隨其后的字符與鍵沖突的情況(請參閱: 123 ),將鍵括在引號和大括號中(或僅用大括號表示整數)以防止語法破壞。


如果要遍歷數組或 object 中的所有元素,則foreach()對兩者都適用。

代碼:(演示

foreach ($response as $key1 => $value1) {
    if (is_scalar($value1)) {
        echo "Key1: $key1, Value1: $value1\n";
    } else {
        foreach ($value1 as $key2 => $value2) {
            echo "Key1: $key1, Key2: $key2, Value2: $value2\n";
        }
    }
}

Output:

Key1: id, Value1: 10499478683521864
Key1: birthday, Value1: 07/22/1983
Key1: email, Value1: email@saya.com
Key1: first_name, Value1: Alan
Key1: gender, Value1: male
Key1: last_name, Value1: Malmsteen
Key1: link, Value1: https://www.facebook.com/app_scoped_user_id/1049213468352864/
Key1: location, Key2: id, Value2: 102173722491792
Key1: location, Key2: name, Value2: Jakarta, Indonesia
Key1: locale, Value1: id_ID
Key1: middle_name, Value1: El-nino
Key1: name, Value1: Alan El-nino Malmsteen
Key1: timezone, Value1: 7
Key1: updated_time, Value1: 2015-05-28T04:09:50+0000
Key1: verified, Value1: 1

您可以使用

$ar = (array) $get_user;

然后您可以按順序訪問它們的索引:

echo $ar[0];
function kPrint($key,$obj){    
return (gettype($obj)=="array"?(array_key_exists($key,$obj)?$obj[$key]:("<font color='red'>NA</font>")):(gettype($obj)=="object"?(property_exists($obj,$key)?$obj->$key:("<font color='red'>NA</font>")):("<font color='red'><font color='green'>:::Exception Start:::</font><br>Invalid Object/Array Passed at kPrint() Function!!<br> At : Variable => ".print_r($obj)."<br>Key => ".$key."<br> At File: <font color='blue'>".debug_backtrace()[0]['file']."</font><br> At Line : ".debug_backtrace()[0]['line']."<br><font color='green'>:::Exception End:::</font></font>")));}

//當你想從數組或 object 訪問項目時,你可以調用這個 function。 這個 function 根據鍵從數組/對象中打印相應的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM