0

I have a array of array data which is came from database. And my "array to xml converter" can convert only one level array.

Basicly I want to convert my database table to xml file.

 public function downloadXml()
{
    $fields = ['created_at', 'updated_at'];
    $products = Product::where('user_id', auth()->id())
               ->exclude($fields)->get()->toArray();// this is returnin array of array like [0 => [], 1 => []]

    $products = array_collapse($products); 
    $result = ArrayToXml::convert($product, 'product');
}

The problem is array_collapse method trim the one level array but give me only last array not all arrays. How can I get all arrays? Any help appreciated..

Edit: when dd(Product::where('user_id', auth()->id()) ->exclude($fields)->get()->toArray(););

Output1 = array:2 [▼ 0 => array:18 [▶] 1 => array:18 [▶] ]

When dd(array_collapse(Product::where('user_id', auth()->id()) ->exclude($fields)->get()->toArray());)

Output2 = array:18 [▶]

I need something like output2 but the problem is output2 assuming there is only one product but actualy there is two product.

Mehmet Dogan
  • 45
  • 1
  • 8
  • [Here's an answer on an SO question with a bunch of answer on how to flatten a standard php array without using laravel.](https://stackoverflow.com/a/46861938/3585500) Maybe one of these will work? – ourmandave Sep 14 '18 at 23:13
  • Would you mind posting an example of the current ->toArray() output, what array_collapse produces and your expected result? I'm guessing flatMap should do the trick, but I am not fully understanding the problem . – Jorge Rodríguez Sep 14 '18 at 23:15
  • thank you @ourmandave I will try those. Let me edit the question with real data. Jorge Rodriguez. – Mehmet Dogan Sep 14 '18 at 23:21
  • @JorgeRodríguez I added the outputs. Please take a look at it. – Mehmet Dogan Sep 14 '18 at 23:31
  • Ok now I understood it. Let me post an answer. – Jorge Rodríguez Sep 14 '18 at 23:47

1 Answers1

0

When performing a database query using Eloquent (Laravel ORM) the results are returned inside a Collection (one per row). This is the 'first level' array you are mentioning.

Unfortunately, a 'second level' array is needed to define the attributes (among others) for every row.

So you either have to:

  1. extend your ArrayToXml converter to work with Laravel collections (i.e. print xml tag, loop through the elements and print the closing xml tag)
  2. Split your xml converter into two pieces: a wrapper for the xml tag opening and closing and your current ArrayToXml::convert inside a map function.

Let me illustrate the latter:

public function downloadXml()
{
    return Product::where('user_id', auth()->id())
       ->get()
       ->map(function (Product $product){
            return ArrayToXml::convert($product->only('id', 'user_id'), 'product');
       })
}