我得到了以下数组:
"task" : {
"author_id" : 150,
"created_at" : somedate,
"status_id" : 2,
"assignee_id" : 100,
"updated_at" : somedate_too
我还有两个关联数组,我按以下方式存储ID的名称:
"100" => Mike,
"150" => Bob //etc..., the same for statuses
我需要检查第一个数组中的ID,并以最有效的方式用相应数组的名称替换数字。我尝试了以下方法:
if(isset(task['status_id'])){$row = array_merge($row, [$status_ids[
task['status_id']]]);}else{$row = array_merge($row, '');}
if(isset(task['author_id'])){row = array_merge($row, [$users[// note the different array here
task['author_id']]]);}else{$row = array_merge($row, '');}
if(isset(task['assignee_id'])){$row = array_merge($row, [$users[
task['assignee_id']]]);}else{$row = array_merge($row, '');}
在我的结果数组($ row)中,我不能错过索引并将其替换为另一个值。如果第一个数组中没有值,我需要插入一个空字符串来获取以下内容,例如:
['in progress', '', 'Mike']
如果第一个数组中没有author_id。我相信应该有一个更好的方法来使用foreach循环,但我不知道如何因为对于不同的字段我从不同的数组获取数据。我不认为每个字段的单独if子句在这里是最合适的。 欢迎任何帮助。谢谢。
答案 0 :(得分:1)
您可以使用引用将特殊键映射到其数组副本,并在填充$row
时使用该映射,如下所示:
$users = [
"100" => "Mike",
"150" => "Bob",
];
$status_ids = [
1 => "Foo",
2 => "Bar",
];
// Define output format and array mapping
$mapping = [
"author_id" => &$users, // Mapped to $users array
"created_at" => null, // Not mapped, keep $task value
"status_id" => &$status_ids,
"assignee_id" => &$users,
"updated_at" => null,
];
$task = [
"author_id" => 150,
"created_at" => "Some date",
"status_id" => 2,
// "assignee_id" => 99999, // Oops, missing key/value => empty string in $row
"updated_at" => "Some other date",
];
foreach ($mapping as $key => $mappedArray) {
@$row[] = $mappedArray
? $mappedArray[$task[$key]] ?: ''
: $task[$key];
}
print_r($row);
输出:
Array
(
[0] => Bob
[1] => Some date
[2] => Bar
[3] =>
[4] => Some other date
)
答案 1 :(得分:0)
它应该工作(我没有尝试,但它应该给你一般的想法):
<?php
$fields = array("author_id", "assignee_id", "status_id");
$aliases = array("users", "users", "status_ids");
foreach ($task as $key=>&$value) {
$alias = str_replace($fields, $aliases, ${$key});
if (is_array(${$alias}) {
$value = array_key_exists($value, ${$alias}) ? ${$alias}[$value] : "";
}
}
unset($value);
然后,您可以直接从$row
阵列按计划填写$task
。