Return with all foreach lines

Asked

Viewed 286 times

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 print_r, return all array lines.

when I give a print_r inside the foreach, it shows all rows 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 outside the foreach, only prints the last line of the array and also does not convert the %produces%:

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

after researching a lot, I discovered that you can add results using .= only that I always get an error something like "you can’t turn array into string"

2 answers

5


To create/return a new array containing the substations of %produz% it takes two steps:

1-Set the new array before foreach.

2 - Use square brackets [] to say that the modification will be done in 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

4

You can also rearrange your code this way:

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

?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.