我需要通过添加缺少的键和值来修改数组中的每个用户对象 - "
目前我有一个while循环,它将每个新值列入数组,名为" Headers"并抓住每个物体并将它们放入用户"阵列。
$headers = array("Firstname", "Lastname", "Email", "Age");
$users = array(
array(
"id" => 32,
"user" => "{
Firstname: 'John',
Lastname: 'Smith',
Email: 'example@pleasehelp.com'
}
),
array(
"id" => 32,
"user" => "{
Firstname: 'Josh',
Lastname: 'Pellow',
Age: '22'
}
)
);
我想要这个:
$users = array(
array(
"id" => 32,
"user" => "{
Firstname: 'John',
Lastname: 'Smith',
Email: 'example@pleasehelp.com',
Age: '-'
}
),
array(
"id" => 32,
"user" => "{
Firstname: 'Josh',
Lastname: 'Pellow',
Email: '-',
Age: '22'
}
)
);
每个用户对象应包含Headers数组中带或不带值的每个值。
答案 0 :(得分:0)
<?php
$headers = array("Firstname", "Lastname", "Email", "Age");
$users = array(
array(
"id" => 32,
"user" => array(
'Firstname'=> 'John',
'Lastname'=> 'Smith',
'Email'=> 'example@pleasehelp.com'
)
),
array(
"id" => 32,
"user" => array(
'Firstname'=> 'Josh',
'Lastname'=> 'Pellow',
'Age'=> '22'
)
));
echo '<pre>';
$i=0;
$newArray=array();
foreach($users as $row){
(isset($row['user']['Firstname']) ? $newArray[$i]['Firstname']= $row['user']['Firstname'] : $newArray[$i]['Firstname']='-');
(isset($row['user']['Lastname']) ? $newArray[$i]['Lastname']= $row['user']['Lastname'] : $newArray[$i]['Lastname']='-');
(isset($row['user']['Email']) ? $newArray[$i]['Email']= $row['user']['Email'] : $newArray[$i]['Email']='-');
(isset($row['user']['Age']) ? $newArray[$i]['Age']= $row['user']['Age'] : $newArray[$i]['Age']='-');
$i++;
}
print_r($newArray);
输出是:
Array
(
[0] => Array
(
[Firstname] => John
[Lastname] => Smith
[Email] => example@pleasehelp.com
[Age] => -
)
[1] => Array
(
[Firstname] => Josh
[Lastname] => Pellow
[Email] => -
[Age] => 22
)
)
答案 1 :(得分:0)
我明白了。我所要做的就是循环每个用户并检查 array_key_exists 中的标题值!
foreach($users as $user){
//get user from user row
$row = $user['user'];
//loop headers for each row
foreach($headers as $header){
//check if $header found in each row
if (!array_key_exists($header,$row)){
//if not found
$row->$header = "-";
}
}
}