从匹配的数组键创建多维数组

时间:2018-03-04 08:12:54

标签: php arrays multidimensional-array

需要通过匹配数组中的键来创建多维数组。

阵列1:

[
 'slide_name_1'  => 'lorem ipsum',
 'slide_title_1' => 'lorem ipsum',
 'slide_name_2'  => 'lorem ipsum',
 'slide_title_2' => 'lorem ipsum',
]

我需要创建这个:

[0] => array (
       'slide_name_1'  => 'lorem ipsum 1',
       'slide_title_1' => 'lorem ipsum 1',
       )
[1] => array (
       'slide_name_2'  => 'lorem ipsum 2',
       'slide_title_2' => 'lorem ipsum 2',
       )

我正在考虑运行一些嵌套的foreach循环并仅匹配键的数字部分(例如:substr($key, strrpos($key, '_') + 1);)。

当然,事实证明这比我预想的要困难得多。任何建议将不胜感激。

1 个答案:

答案 0 :(得分:2)

你走在正确的轨道上。不需要嵌套的foreach循环。只需使用一个。

像:

$arr = array (
 'slide_name_1'  => 'lorem ipsum',
 'slide_title_1' => 'lorem ipsum',
 'slide_name_2'  => 'lorem ipsum',
 'slide_title_2' => 'lorem ipsum',
);

$result = array();
foreach( $arr as $key => $val ){
    $k = substr($key, strrpos($key, '_') + 1); //Get the number of the string after _

    //Normally, this line is actually optional. But for strict PHP without this will create error.
    //This line will create/assign an associative array with the key $k
    //For example, the $k is 1, This will check if $result has a key $k ( $result[1] ) 
    //If not set, It will assign an array to $result[1] = array()
    if ( !isset( $result[ $k ] ) ) $result[ $k ] = array(); //Assign an array if $result[$k] does not exist

    //Since you already set or initiate array() on variable $result[1] above, You can now push $result[1]['slide_name_1'] = 'lorem ipsum 2';
    $result[ $k ][ $key ] = $val . " " . $k; //Push the appended value ( $value and the number after _ )
}

//Return all the values of an array
//This will convert associative array to simple array(index starts from 0)
$result = array_values( $result ); 

这将导致:

阵列

(
    [0] => Array
        (
            [slide_name_1] => lorem ipsum 1
            [slide_title_1] => lorem ipsum 1
        )

    [1] => Array
        (
            [slide_name_2] => lorem ipsum 2
            [slide_title_2] => lorem ipsum 2
        )

)