Return with all the lines of the foreach

6

I have the following script :

<?php
$recursos_data = array(
        array(
                "id" => "0",
                "recurso_nome" => "madeira",
                "producao" => "%produz%",
                "estoque" => "200"
        ),
        array(
                "id" => "1",
                "recurso_nome" => "comida",
                "producao" => "%produz%",
                "estoque" => "100"
        )
);
foreach($recursos_data as $recurso):
        $retornar = preg_replace("/%produz%/", '500', $recursos_data[$recurso['id']]);
endforeach;
return $retornar

?>

I want to give a return, which in print_r , returns all rows in the array.

When I give a print_r inside the foreach, it shows all the lines of the example array:

Array ( [id] => 0
        [recurso_nome] => madeira
        [producao] => 500
        [estoque] => 200 )
        Array ( [id] => 1 
                [recurso_nome] => comida
                [producao] => 500
                [estoque] => 100
        )

And if I give a print_r out of foreach, it only prints the last row of the array and also does not convert the% produces%:

Array ( [id] => 1
        [recurso_nome] => comida
        [producao] => %produz%
        [estoque] => 100
)

After searching a lot, I discovered that you can add results using .= but I always get an error something like "you can not turn array into string"

    
asked by anonymous 28.10.2014 / 00:22

2 answers

5

To create / return a new array containing the %produz% substitutes, two steps are necessary:

1- Define the new array before the foreach.

2 - Use brackets [] to say that the modification will be done on a new item / line.

$arr = array();
foreach($recursos_data as $recurso):
        $arr[] = preg_replace("/%produz%/", '500', $recursos_data[$recurso['id']]);
endforeach;

echo '<pre>';
print_r($arr);

Example

    
28.10.2014 / 00:31
4

You can also rearrange your code like this:

<?php
$recursos_data = array(
        array(
                "id" => "0",
                "recurso_nome" => "madeira",
                "producao" => "%produz%",
                "estoque" => "200"
        ),
        array(
                "id" => "1",
                "recurso_nome" => "comida",
                "producao" => "%produz%",
                "estoque" => "100"
        )
);

$lista_retornar = array();
foreach($recursos_data as $recurso):
        array_push($lista_retornar, preg_replace("/%produz%/", '500',     $recursos_data[$recurso['id']]));
endforeach;

print_r($lista_retornar);

?>
    
28.10.2014 / 01:23