skip to Main Content

I have a nested array and need to format it so it can be written to a single line in a log file.

The entry looks something like this:

$object = [
    'date_time' = date('Y-m-d H:i:s'),
    'user' => 'Mike'
    'actions' => [
        'foo' => 'bar',
        'foo2' => 'bar2'
    ]
];

I’d like to get it to look like this:

2024-03-11 00:00:000,Mike,bar,bar2

I tried to use the implode() function, but it doesn’t seem to work with nested arrays.

Warning: Array to string conversion

2

Answers


  1. $object = [
        'date_time' = date('Y-m-d H:i:s'),
        'user' => 'Mike'
        'actions' => [
            'foo' => 'bar',
            'foo2' => 'bar2'
        ]
    ];
    
    $row = '';
    array_walk_recursive($object, function ($v) use (&$row) { $row .= ($row ? ',' : '') . $v; });
    echo $row;
    
    Login or Signup to reply.
  2. You can achieve this by iterating over each element in the array using a foreach and checks if the current value is an array, then merge the values of that array in the $values. If the current value is not an array, it simply appends it to the $values array.

    <?php
    
    $object = [
        'date_time' => date('Y-m-d H:i:s'),
        'user' => 'Mike',
        'actions' => [
            'foo' => 'bar',
            'foo2' => 'bar2'
        ]
    ];
    
    $values = [];
    
    foreach ($object as $value) {
        if (is_array($value)) {
            $values = array_merge($values, array_values($value));
        } else {
            $values[] = $value;
        }
    }
    
    echo implode(",", $values);
    

    Demo: https://3v4l.org/3Ji57

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search