-1

I've got several arrays which are like this :

$myArray = [
 [
  'value1' => 1,
  'value2' => 2,
  'value3' => 3,
  'objectValue' =>
           'name' => 'toto'
           'age'  => 7,
           'sexe' => 'M'
 ]
[
  'value1' => 11,
  'value2' => 22,
  'value3' => 33,
  'objectValue' =>
           'name' => 'tata'
           'age'  => 77,
           'sexe' => 'F'
 ]
]

I need to access in all my arrays only the property 'name' in objectValue. I started like this :

if is_array($myArray){
  return array_map(
    static function ($params){
     if (is_object($params)) {
      return array_map(
        static function ($param){

          //Here everything is print but I want only the name
          return ['name' => $param]
        }
      )
     }
    }
  )
}

Any idea how to do it ?

Micka Bup
  • 391
  • 1
  • 9
  • 1
    https://www.php.net/manual/en/function.array-column.php – Sysix Nov 10 '21 at 14:38
  • Why not `return $myArray['objectValue']['name'];`? – KIKO Software Nov 10 '21 at 14:39
  • Array_column and the other method (KIKO) doens't work. I edit my example to be more clear – Micka Bup Nov 10 '21 at 14:57
  • 1
    1. Your example array is incorrect format. 2. Your code is wrong and should throw the error because `array_map()` requires 2 parameters but you have only one. Your code did not working. Please correct these 2 checks and please add the result of array format that you want or expect. – vee Nov 10 '21 at 16:54

1 Answers1

0

From your 3rd edit (currently for me)

Your array:

$myArray = [
    [
        'value1' => 1,
        'value2' => 2,
        'value3' => 3,
        'objectValue' => [
            'name' => 'toto',
            'age'  => 7,
            'sexe' => 'M',
        ]
    ],
    [
        'value1' => 11,
        'value2' => 22,
        'value3' => 33,
        'objectValue' => [
            'name' => 'tata',
            'age'  => 77,
            'sexe' => 'F',
        ]
    ]
];

The code:

if (is_array($myArray)) {
    $result = array_map(function($params) {
        if (
            is_array($params) && 
            array_key_exists('objectValue', $params) &&
            is_array($params['objectValue']) && 
            array_key_exists('name', $params['objectValue'])
        ) {
            return ['name' => $params['objectValue']['name']];
        }
    }, $myArray);
    echo '<pre>' . htmlspecialchars(print_r($result, true), ENT_QUOTES) . '</pre>';
}

Result:

Array
(
    [0] => Array
        (
            [name] => toto
        )

    [1] => Array
        (
            [name] => tata
        )
)

I'm not sure is this the result you want. But from your topic:

I need to access in all my arrays only the property 'name' in objectValue.

I think this is it.

vee
  • 4,506
  • 5
  • 44
  • 81