简体   繁体   中英

Array_column() only picking up last part of array

For the life of my I can't figure out how array_column() is working differently for my array than it is for the example in the PHP doc.

Here's my array(retrieved from a return):

  $array = array (
  0 => 
  array (
    'name' => 'Category: Test cat 1',
    'value' => '2',
    'tax' => 'category',
    'selected' => '1',
  ),
  1 => 
  array (
    'name' => 'Category: Uncategorized',
    'value' => '1',
    'tax' => 'category',
    'selected' => '1',
  ),
);

When I output:

$a = array_column($array, 'value', 'tax');        
print_r($a);

The result is:

Array
(
    [category] => 1
)

What i was expecting is:

Array
    (
     [category] => 2
     [category] => 1
    )

I tried making the array like how it is in the PHP doc for array_column() :

$array = array (
  array (
    'name' => 'Category: Test cat 1',
    'value' => '2',
    'tax' => 'category',
    'selected' => '1',
  ),
  array (
    'name' => 'Category: Uncategorized',
    'value' => '1',
    'tax' => 'category',
    'selected' => '1',
  ),
);

I still get the same result

Array
(
    [category] => 1
)

Any explanation as to why I'm not getting the expected array is would be appreciated

If you pass third argument in array_column($array, 'value', 'tax'); like that, it will use third argument as index of the resulting array, in your case you have same value present in the tax key of your inner arrays, so that's why it gets replaced by the value from last array.

You're creating an associative array with duplicate keys, where PHP doesn't play nice. It is replacing the first value each time it runs into the same key.

https://www.php.net/manual/en/function.array-column.php

To make sense of why it "doesn't play nice," try writing your desired output array into a table on a piece of paper, then write what you see back into an array. I think you'll see what the array should look like (couple ways to write it) and why the way you want it to look doesn't make sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM