我有像这样的关联数组
$imagePaths = array(
'logo' => "logo.jpg",
'facebook-logo' => "facebook-icon.jpg",
'twitter-logo' => "twitter-icon.jpg",
'linkedin' => "linkedIn.jpg"
);
我可以打电话给logo,我用下面的代码
$ClassInstance->imagePaths['logo'];
但我也希望能够使用
来调用它$ClassInstance->imagePaths[0];
有没有这样做?
答案 0 :(得分:6)
您可以使用array_keys()
:
$keys = array_keys($imagePaths);
$ClassInstance->imagePaths[$keys[0]];
答案 1 :(得分:4)
您可以使用array_values()
存储第二个数组:
$imagePathsKeyed = array_values($imagePaths);
编辑:我已经扩展了示例代码以帮助
<?php
class SomeObject
{
public $imagePaths;
public $keyedImagePaths;
public function __construct()
{
$this->imagePaths = array(
'logo' => "logo.jpg",
'facebook-logo' => "facebook-icon.jpg",
'twitter-logo' => "twitter-icon.jpg",
'linkedin' => "linkedIn.jpg"
);
$this->keyedImagePaths = array_values($this->imagePaths);
}
}
$classInstance = new SomeObject();
// logo.jpg
echo $classInstance->imagePaths['logo'];
// logo.jpg
echo $classInstance->keyedImagePaths[0];