根据另一个数组

时间:2017-12-27 06:39:27

标签: php arrays sorting

Complete code

我需要根据另一个数组对数组进行排序。目前我有这个函数创建包含用户信息的新数组。

每个用户都以JSON字符串定义,并存储在MySQL中,如下所示:

{"Firstname":"John","Lastname":"Smith","Email":"johnsmith@outlook.com"},
{"Firstname":"Hans","Lastname":"Jobens", "Age", "Too old"}

我循环每个对象以获取每个标头,然后将它们推入标头数组。

$headers = array("Age", "Email", "Firstname", "Lastname")

然后我为每个用户行创建新的用户对象。

$user_object = array();

并将每个标头添加到每个用户对象,并用数据或占位符“ - ”

填充它们
//add missing keys and values
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 = "-";
        }
    }
}

将对象推送到用户数组中,现在看起来像这样:

{"Firstname":"John","Lastname":"Smith","Email":"johnsmith@outlook.com","Age":"-"},
{"Firstname":"Hans","Lastname":"Jobens","Age":"Too old","Email":"-"}

但他们的顺序并不正确。我希望每个用户的对象键都能保持其值,但要按 $ headers 数组排序。

需要的格式:

{"Age":"-","Email":"johnsmith@outlook.com","Firstname":"John","Lastname":"Smith"},
{"Age":"Too old","Email":"-","Firstname":"Hans","Lastname":"Jobens"}

Complete code

编辑:

简称:

  1. 初始化$ list,$ users和$ headers array
  2. 从中获取用户信息数组(存储为javascript对象) MySQL的
  3. 解码并循环每个用户并获取每个对象密钥
  4. 将每个新密钥附加到$ he​​aders array
  5. 再次循环$ users以添加缺失的密钥和占位符(破折号)
  6. 通过$ headers array
  7. 安排OBJECT
  8. 将$ headers和$ users附加到$ list
  9. echo json_encode($ list)
  10. Console.log

3 个答案:

答案 0 :(得分:0)

使用array_replace函数

$user_object = array();
foreach($users as $user){
    // array which set order
    $template = array_fill_keys(["Age", "Email", "Firstname", "Lastname"], '-');
    // Get current existing value
    $user_object[] = array_replace($template, $user['user']);
}
print_r($user_object);

demo

答案 1 :(得分:0)

一种方法是在循环通过(-) if null时推送每个相应的数据 headers

foreach($users as $key => $user){
    //get user from user row
    $row = $user['user'];
    // Set new row
    $newRow = [];
    // Loop thru headers
    foreach ($headers as $header) {
        // Check if row has the header, set '-' if not
        $newRow[$header] = (!array_key_exists($header, $row)) ? '-' : $row[$header];
    }
    // set key of users to newRow
    $users[$key] = $newRow;
}

print_r($users); // Print users

答案 2 :(得分:0)

您可以通过组合uksort()和array_search()使用另一个作为参考来按键排序数组:

uksort($array, function ($a, $b) use ($headers) {
 return array_search($a, $headers) > array_search($b, $headers);
});