1

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.

2
  • 1
    On first blush, put a () at the end of your function definition: (function() { ... whatever ... })(); Nope, javascript on the brain. Use call_user_func. Example coming. Commented Nov 6, 2013 at 18:59
  • I also have javascript on the brain. Commented Nov 7, 2013 at 7:34

2 Answers 2

3

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
)
Sign up to request clarification or add additional context in comments.

Comments

1

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;
            });           

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.