3 回答
TA贡献1831条经验 获得超4个赞
class Person {
public $name = "pname";
public $age = "21";
public $gender = "MaleOrFemale";
function __construct($name,$age,$gender){
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
}
}
您可以使用 OOP 方法并创建一个对象来存储一个人的数据并创建一个人员数组
例子
$steve = new Person("Steve Jobs","60","Male");
这将创建一个名为 steve 的人对象 $steve ,年龄 60 ,性别 Male
您可以根据需要创建可能的人对象并将其放在数组中
$jeff = new Person("Jeff Bezos","50","Male");
$bill = new Person("Bill Gates","64","Male");
将以上所有内容放在一个数组中,如下所示
$persons = array($steve,$jeff,$bill);
尝试下面的代码自学并理解它我使用过对象和构造函数在 w3schools.com 中了解它们
<?php
class Person {
public $name = "pname";
public $age = "21";
public $gender = "MaleOrFemale";
function __construct($name,$age,$gender){
$this->name = $name;
$this->age = $age;
$this->gender = $gender;
}
}
$steve = new Person("Steve Jobs","60","Male");
$jeff = new Person("Jeff Bezos","50","Male");
$bill = new Person("Bill Gates","64","Male");
$persons = array($steve,$jeff,$bill);
foreach($persons as $person){
echo"Person Name : ".$person->name."<br>";
echo"Person Age : ".$person->age."<br>";
echo"Person Gender : ".$person->gender."<br><br>";
}
?>
TA贡献1834条经验 获得超8个赞
一个简单的循环将在这里执行:
<?php
$names = ["john","mell","ben","henz","len"];
$ages = ["10","15","58","12","13"];
$genders = ["male","female","male","male","female"];
for($i=0, $c=count($names), $out=[]; $i<$c; $i++) {
$out[] = [
'name' => $names[$i],
'age' => $ages[$i],
'gender' => $genders[$i]
];
}
var_export($out);
输出:
array (
0 =>
array (
'name' => 'john',
'age' => '10',
'gender' => 'male',
),
1 =>
array (
'name' => 'mell',
'age' => '15',
'gender' => 'female',
),
2 =>
array (
'name' => 'ben',
'age' => '58',
'gender' => 'male',
),
3 =>
array (
'name' => 'henz',
'age' => '12',
'gender' => 'male',
),
4 =>
array (
'name' => 'len',
'age' => '13',
'gender' => 'female',
),
)
您可以将 for 循环换成 foreach:
foreach ($names as $k => $v) {
$out[] = [
'name' => $names[$k],
'age' => $ages[$k],
'gender' => $genders[$k]
];
}
TA贡献1804条经验 获得超8个赞
我认为@ajay-kumar 提供的array_map 解决方案是最好的,我会提出一个更动态和更易于阅读的解决方案
function bindDatas(&$resultSolution, $inputData, $keyName)
{
foreach ($inputData as $key => $value) {
$resultSolution[$key][$keyName] = $value;
}
}
一些人认为的测试代码是这样的:
//your code here
bindDatas($resultSolution, $arrayname, 'name');
bindDatas($resultSolution, $arrayage, 'age');
bindDatas($resultSolution, $arraygender, 'gender');
echo '<pre>';
print_r($resultSolution);
echo '</pre>';
确实,$key 变量引用了 $inputData 中的位置,但我们在这里使用它是因为我们希望保持全局数组中的顺序
- 3 回答
- 0 关注
- 126 浏览
添加回答
举报