문제

I have this code chunk

        $data['cp'][$key]->prominence           = $meta_data['prominence'];
        $data['cp'][$key]->related_link = (function()
        {   $arr = array();
            for ( $i = 1; $i < 4 ; $i++ ) {
                $rldata = array();
                $rldata['title'] = $metadata['related_link_'.$i.'_title'];
                $rldata['title'] = $metadata['related_link_'.$i.'_url'];
                array_push( $arr, $rldata );
                }
            return  $arr;
        });

As you can see, I want $data['cp'][$key]->related_link to be equal to a multidimensional array dynamically generated by the anonymous function.

However when using print_r it just shows the key as being equal to a Closure. How do I edit the code so it actually returns the array, rather than just being equal to a closure.

도움이 되었습니까?

해결책

How about this:

<?php

$x = (function () { return array (1, 2, 3); });
$y = call_user_func(function () { return array (1, 2, 3); });
print_r($x);
print_r($y);

?>

results:

Closure Object
(
)
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

다른 팁

You should execute the function, until now you are just declaring it

$data['cp'][$key]->prominence   = $meta_data['prominence'];
$data['cp'][$key]->related_link = call_user_func(function()
            {   $arr = array();
                for ( $i = 1; $i < 4 ; $i++ ) {
                    $rldata = array();
                    $rldata['title'] = $metadata['related_link_'.$i.'_title'];
                    $rldata['title'] = $metadata['related_link_'.$i.'_url'];
                    array_push( $arr, $rldata );
                    }
                return  $arr;
            });           
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top