Access data from an Array that receives 2 Arrays

Asked

Viewed 1,986 times

2

Let’s say I have an Array $testes that receives 2 Arrays $variavel1 and $variavel2. So I do $this->set('testes', $testes) to use in the view.

In View how I access the values of $variavel1 and $variavel2 ? I made a foreach and tried $testes['$variavel1']['campo'], but it only gives one Undefined Index in $variavel1.

Example, how to access data from this Array?

Array (
    [0] => Array (
        [ProcuraProdutoPedOnline] => Array (
            [cd_familia] => 3
            [ds_familia] => ACESSORIOS
        )
    )
    [1] => Array (
        [ProcuraProdutoPedOnline] => Array (
            [cd_familia] => 1
            [ds_familia] => CALCADOS
        )
    )
)

And

Array (
    [0] => Array (
        [VwEstPedOnline] => Array (
            [cd_seq_pedido] => 2034
        )
    )
    [1] => Array (
        [VwEstPedOnline] => Array (
            [cd_seq_pedido] => 2038
        )
    )
)

$testes is receiving like this : $testes = array($cdSeqPeds, $familias);

2 answers

4

To walk the array, do so:

$array = array("0" => array ( "ProcuraProdutoPedOnline" => array(
                              "cd_familia" => 3,
                              "ds_familia" => "ACESSORIOS")
                             ),
                "1" => array ( "ProcuraProdutoPedOnline" => array(
                               "cd_familia" => 1,
                               "ds_familia" => "CALCADOS")
                             )
               );

foreach ($array as $indices) {
    foreach($indices as $pedidos){
        foreach ($pedidos as $chave => $pedido){
            echo "$chave = $pedido\n";
        }
    }
}

To directly access a value, it is necessary to specify the index, the subarray and the key. So:

echo $array[0]["ProcuraProdutoPedOnline"]["ds_familia"];

See demonstração

1

You have the answer in your own question. If there are two vectors within one, you first need to identify which of the two is your object. Of course it is important to check if the index really exists.

For example, for the first object of your first example:

$testes[0]['ProcuraProdutoPedOnline']['cd_familia']

And for the second object:

$testes[1]['ProcuraProdutoPedOnline']['cd_familia']

Within a foreach, for example:

foreach ($testes as $obj) {
    // $obj['ProcuraProdutoPedOnline']['cd_familia']
}

Of course, in the foreach does not need since it makes the loop on the elements within $testes.

  • I’ve tried it this way, it only prints 2034 due to [0], and identifies Procuraprodutopedonline as Undefined, and cd_familia null.

Browser other questions tagged

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