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.

1
  • how many levels do you have? is the depth fixed? Commented Nov 29, 2019 at 20:00

4 Answers 4

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"
}
Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

1

Use foreach statement will be solved your case

$newarray = array();
foreach($array['level1'] as $randomItemKey => $randomItemValue){
   $newarray[] = $randomItemValue['attr2'];
}

1 Comment

You can drop the key if not needed: foreach($array['level1'] as $value)
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;
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.