2016-11-23 37 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

相关问题