[英]create multidimensional array from matching array keys
需要通過匹配數組中的鍵來創建多維數組。
陣列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);
)。
當然,事實證明這比我預期的要困難。 任何建議將不勝感激。
您走在正確的軌道上。 雖然不需要嵌套的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
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.