0

I have an array of PHP objects (lets say orders) which have arrays of items like so (JSON for ease of notation):

$orders = [
  {
    id: 87,
    user_id: 6,
    menu_id: 9,
    items: [
      {
        id: 1,
        name: "Item 1",
      }
    ]
  },
  {
    id: 88,
    user_id: 3,
    menu_id: 6,
    items: [
      {
        id: 2,
        name: "Item 2",
      }
    ]
  }
]

I'm trying to make a CSV row with titles of this kind of array. I'm using a keyed array like so:

$settings = [
  'Order ID' => 'id',
  'User ID' => 'user_id'
];

So now I can go...

$csv = [];
$csv[] = array_keys($settings);

foreach($orders as $order):

    $csv_row = [];

    foreach($settings as $column);
      $csv_row[] = $order->{$column};
    endforeach;

    $csv[] = $csv_row;

endforeach;

This gives me:

[ 'Order ID',   'User ID' ]
[ '87',         '6' ]
[ '88',         '3' ]

Is there any way I can dynamically access the 'deeper' variables? i.e. $order->items[0]->name, in a similar way to the curly bracket notation? I need to do it dynamically as there are lots of different object and relations that I need to export as CSV files.

P.S. Its really late – sorry if this is a crazy question

1
  • they're just arrays, so $order[0]['name']? You can't build that kind of array "path" dynamically without resorting to evil stuff like eval, but if you know how "deep" into the array you have to go, you can easy do $order[$a][$b][$c]... Commented Jul 30, 2015 at 21:39

1 Answer 1

2

You can't use the curly braces notation to get deeper than one level. What you could do is to use a helper function that would let you fetch values by multi-level key.

An example function could be:

function getByPath($value, array $path)
{ 
  if (empty($path)) return $value;
  if (!is_array($value)) return;
  if (array_key_exists($path[0], $value)) return getByPath($value[$path[0]], array_slice($path, 1));
}

Example usage pattern for your case could be:

$settings = [
  'Order ID' => ['id'],
  'User ID' => ['user', 'id'],
  'User Name' => ['user', 'name'],
  'Item 0 Name' => ['item', 0, 'name'],
  'Item 0 Price' => ['item', 0, 'price']
];

foreach($settings as $path);
  $csv_row[] = getByPath($order, $path);
endforeach;
Sign up to request clarification or add additional context in comments.

2 Comments

basically what I was about to say. slightly different code.
If you weren't stuck in the internet, I would kiss you.

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.