我正在试验数据收集对象,并希望使用类构造对传递给新实例化对象的数组的数组键进行更改。
其主要思想是可以用数字键传递数组,然后将每个数字键替换为字符串值。系统的前提是,数组只包含一个数组,每个数组包含三个键/值对。(见数据示例)。我知道这是非常脆弱的,我打算接下来讨论这个问题。
类:
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..
];
发布于 2017-09-10 12:01:04
您可以使用所需的键创建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
循环中的实际元素。你也应该根据你的需要做一些验证。
作为附带说明,您应该使用在构造函数中不执行任何工作。。会给你带来麻烦的。最好让另一个函数使用您的输入值进行初始工作:
<?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();
发布于 2017-09-10 12:00:03
只需创建临时数组并将其分配给集合。将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;
}
https://stackoverflow.com/questions/46140347
复制相似问题