我有一个来自的数组和像这样的API
array(
'data' => array(
'id' => 0,
'attributes' => array(
'title' => 'title'
),
'itemdetails' => array(
'id' => 0,
'attributes' => array(
'title' => '',
'images' => array(
'original' => '',
'thumbnails' => array(
'thumb',
'thumb'
)
)
)
)
)
);
所以,如果我想获得我必须做的图像
$array['data']['itemdetails']['attributes']['images']['thumbnails']
有没有办法让我能做到
$array->getImageThumbnails()
非常感谢提前!
答案 0 :(得分:1)
我可能会后悔,但这是一个简单的实现:
class someClass {
public $array;
public function __construct($array) {
$this->array = $array;
}
public function getImageThumbnails() {
return $this->array['data']['itemdetails']['attributes']['images']['thumbnails'];
}
}
然后只是:
$object = new someClass($array);
$thumbs = $object->getImageThumbnails();
答案 1 :(得分:0)
一种解决方案是创建一个将在其构造函数中接受此数组的对象,并在该对象上定义所需的方法:
class MyImage {
protected $data = array();
public function __construct($data)
{
$this->data = $data['data'];
}
public function getImageThumbnails()
{
return $this->data['itemdetails']['attributes']['images']['thumbnails'];
}
}
获得数据后,在代码中实例化此对象:
$data = getStuffFromAPI();
$image = new MyImage($data);
return $image->getImageThumbnails();
答案 2 :(得分:0)
如何将多维数组转换为对象:(Singleton
方法)
class ArrayConvertor {
private static $obj;
private __construct(){}
private __clone(){}
public static function convertToObject($array = []) {
self::$obj = is_array($array) ? (object) array_map("self::convertToObject",$array) : $array;
return self::$obj;
}
public static function getImageThumbnails() { // assuming specific array structure
$thumbs = null;
if (is_object(self::$obj)){
$thumbs = self::$obj->data->itemdetails->attributes->images->thumbnails;
}
return $thumbs;
}
}
$obj = ArrayConvertor::convertToObject($arr);
var_dump(ArrayConvertor::getImageThumbnails());