如何创建将元素推入数组的函数?

时间:2016-11-23 16:49:37

标签: php wordpress

试图弄清楚为什么这个函数不能将任何东西推到我定义的数组中。当我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);

1 个答案:

答案 0 :(得分: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);

您会注意到我在函数声明中添加了&,因此它可以指向该确切变量并更改其内容。