Cronas De Se
Cronas De Se

Reputation: 331

Loop throuh array of arrays PHP

I have an array that I got from my $_POST data with this values

Array ( 
    [unit] => 
    [items] => Array ( 
        [1] => Array ( 
            [category] => 1 
            [items] => 5 
            [qty] => 1 
            [jan] => 1 
            [feb] => 
            [mar] => 
            [apr] => 
            [may] =>
            [jun] => 
            [jul] => 
            [aug] => 
            [sep] => 
            [oct] => 
            [nov] => 
            [dec] => 
        ) 
        [2] => Array ( 
            [category] => 1 
            [items] => 20 
            [qty] => 1 
            [jan] => 1 
            [feb] => 
            [mar] => 
            [apr] => 
            [may] => 
            [jun] => 
            [jul] => 
            [aug] => 
            [sep] => 
            [oct] => 
            [nov] => 
            [dec] => 
        ) 
        [3] => Array ( 
            [category] => 1 
            [items] => 27 
            [qty] => 1 
            [jan] => 1 
            [feb] => 
            [mar] => 
            [apr] => 
            [may] => 
            [jun] => 
            [jul] => 
            [aug] => 
            [sep] => 
            [oct] => 
            [nov] => 
            [dec] => 
        ) 
    ) 
    [action] => 
)

I'm trying to get each array and pass it to my model for database insertion. For example get the array of [items] where [1] points.

I have tried using

$array_col = array_column($_POST, 'items');
print_r($array_col);

but it returns Array() which is empty.

Thank you for the answers.

Upvotes: 0

Views: 56

Answers (3)

Ali Zia
Ali Zia

Reputation: 3875

You can use this code.

foreach($_POST['items'] as $a){
    // Code will go here. Whatever.
    print_r($a);
}

Upvotes: 0

xpy
xpy

Reputation: 5621

I suspect that your data are in $_POST['items']. so:

$array_col = $_POST['items'];

Then, to iterate through them you need a loop.

foreach($array_col as $col){
  // Do your stuff here
  print_r($col);
}

Upvotes: 1

Vijay Sai Chaudary
Vijay Sai Chaudary

Reputation: 177

From PHP documentation ...
http://php.net/manual/en/function.array-column.php
array_column() returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.

Check you have array key index - 'items' are in various levels (level-0 and also in level 2)

Upvotes: 1

Related Questions