我試圖插入一個PHP數組到一個MySQL數據庫,但我遇到了這個特定數組的麻煩。我試圖創建一個函數,它Flatten索引數組
array(0 => array ('col1' => 'value', 'col2' => 'value', 'col3' => 'value', 'col4' => value', 'col5' => 'value', 'col6' => array ('string' => array ('col7' => 'value' , 'col8' => 'value'),),),
1 => array ('col1' => 'value', 'col2' => 'value', 'col3' => 'value', 'col4' => array (), 'col5' => 'value', 'col6' => array ('string' => array (),), ),
2 => array ('col1' => 'value', 'col2' => 'value', 'col3' => 'value', 'col4' => array (), 'col5' => 'value', 'col6' => array ('string' => array (),),),)
和方式隔開每個編號的排列和格式它:
array('col1' => 'value', 'col2' => 'value', 'col3' => 'value', 'col4' => 'value', 'col5' => 'value', ['col6' => 'value','col7' => 'value',])
array('col1' => 'value', 'col2' => 'value', 'col3' => 'value', 'col4' => 'value', 'col5' => 'value', ['col6' => 'value','col7' => 'value',])
array('col1' => 'value', 'col2' => 'value', 'col3' => 'value', 'col4' => 'value', 'col5' => 'value', ['col6' => 'value','col7' => 'value',])
取決於有多少行也有。請記住這些條件:
+8 cols is just an example, the range can fluctuate greatly.
+Cols containing a array must be non existent if it empty, like in [1] and [2], but not [0].
+Any column could contain a empty or full array. if it contains a full array, it needs to be flatten while retaining it's value.
+Some arrays might have greater then 2 nested arrays. (elements)
+Not all of the arrays have nested arrays, they are already formatted correctly. These arrays can not be affected by the PHP function i'm trying to create.
我很難過,我創建的每個函數都失敗了。謝謝大家提前。我使用Var_export
這個函數獲取上面的數組。
function flatten($array, $preserve_keys = false)
{
if (!$preserve_keys) {
$array = array_values($array);
}
$flattened_array = array();
foreach ($array as $k => $v) {
$flattened_array[$k] = $v;
if (is_array($v)) {
$flattened_array = array_merge($flattened_array, call_user_func(__FUNCTION__, $v, $preserve_keys));
} elseif ($preserve_keys) {
$flattened_array[$k] = $v;
} else {
$flattened_array[] = $v;
}
}
return (array)$flattened_array;
}
你怎麼想他們被夷爲平地,我們應該添加的cols,還是會與所有的值(而不是陣列的字符串)> – pzirkind
Thanks @pzirkind,包含數組的單個鍵/值需要用包含的列和值替換。 所以,它需要仍然是一個數組。 –
啊,那麼我們要扁平化(如果數組仍然存在) – pzirkind