在讀wordpress taxonomy.php 原始碼時,遇到數組的建立問題,概括起來就是:
$arrayname[item]=value 與 $arrayname[item][]=value 有什麼區別嗎?在這個例子中,其實就是 數/值交換了下位置,是嗎? 請達人指教。
function _get_term_hierarchy( $taxonomy ) 中:
$children = array();
$terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent'));
foreach ( $terms as $term_id => $parent ) {
if ( $parent > 0 )
$children[$parent][] = $term_id;
}
在 function get_terms( $taxonomies, $args = '' )中:
$_terms = array();
if ( 'id=>parent' == $_fields ) {
foreach ( $terms as $term ) {
$_terms[ $term->term_id ] = $term->parent;
}
}
回複討論(解決方案)
首先 你[ ] 裡面不是變數 需要用引號引起來吧 不然..... $arrayname[item]=value 這個是一維數組 將數組$arrayname 建名為 'item' 的元素的值 為 value 而 $arrayname['item'][] = value 是二維數組 將數組$arrayname['item']的下級數組的當前位置的值設為 value
$children[$parent][]
$children[$parent]=可能是一個數組(子項可能很多啊,可以是一個數組)
$_terms[ $term->term_id ] = $term->parent;
$_terms[ $term->term_id ]=只能是一個值(父項只能是一個啊)
對否
$_terms[ $term->term_id ] = $term->parent;
用來收集每個 term_id 的 parent 節點(term_id 是唯一的)
$children[$parent][] = $term_id;
用來聚類子節點
前者是直接賦值。
後者是建立數組,然後追加入最後一個元素。
前者是直接賦值。
後者是建立數組,然後追加入最後一個元素。
--‘建立數組,然後追加入最後一個元素’是什麼意思?不理解。
$_terms[ $term->term_id ] = $term->parent;
用來收集每個 term_id 的 parent 節點(term_id 是唯一的)
$children[$parent][] = $term_id;
用來聚類子節點
----能理解
$arrayname[item]=value 與 $arrayname[item][]=value 構造成的數組,分別是這樣的,對嗎?
$aaa = array (
3=>7,
6=>9 )
$bbb= array (
3=>array(
0=>8,
1=>4,
)
)
後者是建立數組,然後追加入最後一個元素。
--‘建立數組,然後追加入最後一個元素’是什麼意思?不理解。
對於
foreach ( $terms as $term ) {
$_terms[ $term->term_id ] = $term->parent;
}
由於賦值是在迴圈中執行的
如果 $term->term_id 不唯一,即 $term->term_id 重複出現
那麼,$_terms[ $term->term_id ] 就是最後一次 相同 $term->term_id 的 $term->parent