2016-11-23 83 views
0

試圖找出爲什麼這個函數不會將任何東西推到我定義的數組上。當我print_r $ location_matches它是空的。如何創建將元素推入數組的函數?

$id = get_the_ID(); 
$location_matches = array(); 

function find_location_meta($location_id, $product_id, $location_matches_arr) { 
    $meta_info = get_post_meta($location_id); 
    $working_with = unserialize($meta_info[locations_products_carried][0]); 
    for ($i = 0; $i < count($working_with); $i++) { 
     if ($working_with[$i][locations_products][0] == $product_id) { 
      array_push($location_matches_arr, $working_with[$i]); 
     } 
    } 
} 

find_location_meta(94, $id, $location_matches); 
+0

您需要要麼返回你的數組或引用傳遞。 –

+0

$ working_with = unserialize($ meta_info [locations_products_carried] [0]); - locations_products_carried是一個變量 - 那麼你需要$符號,或者它是一個字符串,那麼你需要引號,如果我認爲是正確的。嘗試「print_r」 - $ meta_info和/或$ working_with - 我建議你一步一步來。檢查$ working_with是否在迭代它之前有任何元素,並且locations_products存在問題(它是變量或字符串!)。 94是一個正確的$ location_id肯定嗎? –

回答

2

你需要做參照一個通道,如果你想改變一個變量的方式這樣:

$id = get_the_ID(); 
$location_matches = array(); 

function find_location_meta($location_id, $product_id, &$location_matches_arr) { 
    $meta_info = get_post_meta($location_id); 
    $working_with = unserialize($meta_info[locations_products_carried][0]); 
    for ($i = 0; $i < count($working_with); $i++) { 
     if ($working_with[$i][locations_products][0] == $product_id) { 
      array_push($location_matches_arr, $working_with[$i]); 
     } 
    } 
} 

find_location_meta(94, $id, $location_matches); 

你會注意到我在函數的聲明添加&所以它可能指向那個確切的變量並且改變它的內容。

+0

工作完美,謝謝! – user3006927

相關問題