如何根据 PHP 中关联数组的值创建变量数组?

How can I create an array of variables based on an associative array's value in PHP?

给定以下数组

 ( 
 0 => array( 
     'orders_messaging_info_id' => '1',
     'column_name' => 'message_route',
     'column_info' => 'internal',
     ),
 
 1 => array(
     'orders_messaging_info_id' => '2',
     'column_name' => 'message_route',
     'column_info' => 'external',
     ),
 
 2 => array(
     'orders_messaging_info_id' => '3',
     'column_name' => 'message_type',
     'column_info' => 'SMS',
     ),
 
 3 => array(
     'orders_messaging_info_id' => '4',
     'column_name' => 'message_type',
     'column_info' => 'email',
     ),
 
 4 => array(
     'orders_messaging_info_id' => '5',
     'column_name' => 'message_type',
     'column_info' => 'slack',
     ),
 
 5 => array(
     'orders_messaging_info_id' => '6',
     'column_name' => 'message_type',
     'column_info' => 'plaintext',
     ),
 
 6 => array(
     'orders_messaging_info_id' => '10',
     'column_name' => 'message_text',
     'column_info' => 'JSON',
     ),
 )

如何创建三个以 'column_name' 的值命名的关联数组,其键是 'orders_messaging_info_id' 的值,值是 'column_info'?

我尝试在 'column_name' 的值的 foreach 循环中使用 extract() 来创建三个变量——每个变量对应一个不同的值——但我不知道如何访问其他两个值每个数组来分配它们。一旦我解决了这个问题,我知道我必须想出一种方法来向 extract() 创建的数组添加值,例如使用将被命名为 $message_type[]$message_route[] 的数组变量

预期的数组看起来像

$message_route = array('1'=>'internal','2'=>'external');

extract() 在这里并不能真正帮助你。相反,您应该使用可变变量 (https://www.php.net/manual/en/language.variables.variable.php)。类似于:

<?php

$array = array(
 0 => array( 
     'orders_messaging_info_id' => '1',
     'column_name' => 'message_route',
     'column_info' => 'internal',
     ),
 1 => array(
     'orders_messaging_info_id' => '2',
     'column_name' => 'message_route',
     'column_info' => 'external',
     ),
 2 => array(
     'orders_messaging_info_id' => '3',
     'column_name' => 'message_type',
     'column_info' => 'SMS',
     ),
 3 => array(
     'orders_messaging_info_id' => '4',
     'column_name' => 'message_type',
     'column_info' => 'email',
     ),
 4 => array(
     'orders_messaging_info_id' => '5',
     'column_name' => 'message_type',
     'column_info' => 'slack',
     ),
 5 => array(
     'orders_messaging_info_id' => '6',
     'column_name' => 'message_type',
     'column_info' => 'plaintext',
     ),
 6 => array(
     'orders_messaging_info_id' => '10',
     'column_name' => 'message_text',
     'column_info' => 'JSON',
     ),
 );
 
 foreach($array as $entry) {
     $name = $entry['column_name'];
     if (!isset($$name)) {
        $$name = [];    
     }
     $$name[$entry['orders_messaging_info_id']] = $entry['column_info'];
 }
 
 var_dump($message_text, $message_route, $message_type);