-2

I have following codes:

$data = [
    ['foo' => 1, 'bar' => 3],
    ['foo' => 2, 'bar' => 4]
];


function go($coming_data, $run) {

    foreach($coming_data as $item) {
        return $run;
    }

}

echo go($data, $item['bar']);

and, i need get 34 output, i should use this structure because this codes running my custom table creator bla bla, so i should like as $item['bar'] variables as function parameter but this is not recognized in foreach loop on function.

so, all I need is to be able to define the $item variable in the function like use eval recursive

How can i do in this situation ? Thanks for your helps.

Jeremy
  • 88
  • 7

2 Answers2

0

Instead of passing it the actual code that you'd type, pass it the string value of the key you want to collect.

This assumes that your data will be an indexed array composed of either indexed or associative arrays (or both!). It loops through the array and if there is a matching key it starts building the return string or adds it to the return string. Personally I'd look at changing the $retval string into an array and returning that to the calling location...

<?php

$data = [
    ['foo' => 1, 'bar' => 3],
    ['foo' => 2, 'bar' => 4]
];


function go($coming_data, $run) {

    for($i=0;$i<count($coming_data);$i++){
        if(isset($coming_data[$i][$run])){
            if(!isset($retval)){
                $retval=$coming_data[$i][$run];
            }else{
                $retval.=$coming_data[$i][$run];
            }
        }
    }

    return $retval;

}

echo go($data, 'bar');

?>
ivanivan
  • 2,155
  • 2
  • 10
  • 11
  • Unless you magically see something that I don't, the question makes no sense. – AbraCadaver Feb 23 '18 at 02:24
  • @AbraCadaver based on that last sentence in italics, i think he wants to be able to call a rather generic function that will return the values of all array elements with a key/index that is named as an argument to the function. At least, that is the question I attempted to answer :) – ivanivan Feb 23 '18 at 02:31
0

Just use generator and key param as string:

<?php

$data = [
    ['foo' => 1, 'bar' => 3],
    ['foo' => 2, 'bar' => 4]
];


function go($coming_data, $run) {

    foreach($coming_data as $item) {
        yield $item[$run];
    }

}

$output = go($data, 'bar');

foreach ($output as $out) {
    echo $out;
}