-2

I run the following to get an array of customs_port_id, among other info:

$this->data['port_datas_selects'] = $this->MH_customs_port_model->customs_port_read($customs_id); 

The above returns the following array:

Array ( 
    [0] => Array ( 
       [customs_port_pk] => 35 
       [customs_port_id] => 735 
       [customs_id] => 19 
     ) 
    [1] => Array (
       [customs_port_pk] => 36 
    [customs_port_id] => 732 
    [customs_id] => 19 
    ) 
 ) 

The array length is unknown. How can I put customs_port_id into a simple array like (735,732)?

I tried something like this but it just returns the last customs_id.

    $x = array();
    foreach ($this->data['port_datas_selects'] as $port_datas_select) {
        $x += array($port_datas_select['customs_port_id']);
    }
    print_r($x);

The above returns:

   Array ( [0] => 735 )

I also tried .= instead of += but doesn't work.

spreaderman
  • 918
  • 2
  • 10
  • 39
  • 1
    You might be looking for [array_column()](https://www.php.net/manual/en/function.array-column.php). Use it like: `$x = array_column($this->data['port_datas_selects'], 'custom_port_id');`. That will give you an array with all the values from the that column. – M. Eriksson May 24 '20 at 08:22
  • replaced the one line in the foreach look to $x = array_column($port_datas_select, 'customs_port_id'); and just get array() with nothing as output. – spreaderman May 24 '20 at 08:32
  • If I do this, $x += array($port_datas_select['customs_port_id']); I get Array ( [0] => 735 ) but that's just one... it did add the other one. – spreaderman May 24 '20 at 08:38
  • Remove your loop. The line I posted replaces the loop completely. That function does it all for you. I linked to the manual about it in my comment. – M. Eriksson May 24 '20 at 08:44

1 Answers1

3

To add an element to an array in php you have to use square brackets, like this:

$x = [];
foreach ($this->data['port_datas_selects'] as $port_datas_select) {
    $x[] = $port_datas_select['customs_port_id'];
}
print_r($x);

In a more elegant way you can use array_column as mentioned in the comment.

$x = array_column($this->data['port_datas_selects'], 'customs_port_id')
Giacomo M
  • 4,450
  • 7
  • 28
  • 57