我正在试验数据集合对象,并希望使用类构造来更改传递给新实例化对象的数组的数组键。
主要思想是数组可以使用数字键传递,然后每个数字键将替换为字符串值。系统的前提是数组只有一个数组,每个数组包含三个键/值对。 (见数据示例)。我知道这非常脆弱,我打算接下来解决这个问题。
类别:
class newsCollection {
private $collection;
public function __construct($data)
{
foreach ($data[0] as $key => $value) {
switch ($key) {
case 0:
// Replace key ID with a string ie. 0 with "headline"
break;
case 1:
// Replace key ID with a string ie. 1 with "date"
break;
case 2:
// Replace key ID with a string ie. 2 with "author"
break;
}
}
$this->collection = $data;
}
public function getNewsCollection()
{
return $this->collection;
}
}
数据(数组):
$sports = [
[
"Boston Red Sox vs New York Yankees - 9-3",
"19.06.2017",
"ESPN"
],
[
"Boston Patriot QB breaks new record!",
"16.07.2017",
"NESN"
],
[
"Celtics coach John Doe inducted into hall of fame",
"25.07.2017",
"Fox Sports"
],
[
"Boston Brewins win 16-5 against New York's Rangers",
"21.08.2017",
"NESN"
]
];
渴望结果的例子:
$sports = [
[
"headline" => Boston Red Sox vs New York Yankees - 9-3",
"date => "19.06.2017",
"author" => "ESPN"
],
ect..
];
答案 0 :(得分:1)
只需创建临时数组并将其分配给集合。将您的constructor
更改为:
public function __construct($data)
{
$new_data = array();
foreach ($data as $key => $value) {
if(is_array($value))
{
$new_data_tmp["headline"] = isset($value[0])?$value[0]:"";
$new_data_tmp["date"] = isset($value[1])?$value[1]:"";
$new_data_tmp["author"] = isset($value[2])?$value[2]:"";
$new_data[] = $new_data_tmp;
}
}
$this->collection = $new_data;
}
答案 1 :(得分:1)
您可以使用所需的密钥制作array
,然后使用array_combine()
将其设置为输入array
的键。像这样:
private $keys = [
"headline",
"date",
"author",
];
// ...
public function __construct($data)
{
foreach ($data as &$el) {
$el = array_combine($this->keys, $el);
}
$this->collection = $data;
}
注意它是通过引用完成的,所以我们正在修改foreach
循环中的实际元素。您还应该根据自己的需要进行一些验证。
作为旁注,你应该not do any work in the constructor。它将带给你未来的问题。最好让另一个函数使用输入值进行初始工作:
<?php
class newsCollection {
private $collection;
private $keys = [
"headline",
"date",
"author",
];
public function __construct($data)
{
$this->collection = $data;
}
public function assingKeys() {
foreach ($this->collection as &$el) {
$el = array_combine($this->keys, $el);
}
}
public function getNewsCollection()
{
return $this->collection;
}
}
$c = new newsCollection($sports);
$c->assignKeys();
$collection = $c->getNewsCollection();