1

I have a PHP array like this...

[level1] => Array
(
    [random475item] => Array
        (
            [attr1] => tester1
            [attr2] => tester2
            [attr3] => tester3
        )
    [random455item] => Array
        (
            [attr1] => tester1
            [attr2] => tester2
            [attr3] => tester3
        )
)

I am trying to get the values of the attr2 fields in a new array. I can specify a specific like this...

$newarray = array();
newarray [] = $array['level1']['random475item']['attr2'];
newarray [] = $array['level1']['random455item']['attr2'];

But is there a way to automate this as it could be 50 random items coming up and I don't want to have to keep adding them manually.

  • how many levels do you have? is the depth fixed? – mrbm yesterday
2

https://www.php.net/manual/en/function.array-column.php and the code below at https://3v4l.org/8j3ae

<?php 
$array = ['level1' => [
    'item1' => [
        'attr1' => 'test1',
        'attr2' => 'test2',
        'attr3' => 'test3'
    ],
    'item2' => [
        'attr1' => 'test4',
        'attr2' => 'test5',
        'attr3' => 'test6'
    ],
]];

$values = array_column($array['level1'], 'attr2');

var_dump($values);

creates

array(2) {
  [0]=>
  string(5) "test2"
  [1]=>
  string(5) "test5"
}
1

You can use array_map for that :

$array = ['level1' => [
    'item1' => [
        'attr1' => 'test1',
        'attr2' => 'test2',
        'attr3' => 'test3'
    ],
    'item2' => [
        'attr1' => 'test4',
        'attr2' => 'test5',
        'attr3' => 'test6'
    ],
]];

// parse every item
$values = array_map(function($item) {
    // for each item, return the value 'attr2'
    return $item['attr2'];
}, $array['level1']);

I have created a sandbox for you to try;

1

Use foreach statement will be solved your case

$newarray = array();
foreach($array['level1'] as $randomItemKey => $randomItemValue){
   $newarray[] = $randomItemValue['attr2'];
}
  • 1
    You can drop the key if not needed: foreach($array['level1'] as $value) – Progrock yesterday
1

If the values can occur at any point in the array, you can use array_walk_recursive() which will loop through all of the values (only leaf nodes) and you can check if it is an attr2 element and add it into an output array...

$out = [];
array_walk_recursive($array, function ($data, $key ) use (&$out)    {
    if ( $key == "attr2" )  {
        $out[] = $data;
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.