S
S
Sergey Ilyin2018-04-25 16:51:41
PHP
Sergey Ilyin, 2018-04-25 16:51:41

How can I use a foreach or for loop to transfer data from one array to another for subsequent output in XML?

There is an XML generator (a third-party module connected to a Yii2 application). Now one last entry is output in XML, but it is necessary that all of them are output ... How to do it, help, I have already broken my head)

//Выборка из БД
$results = Markers::findBySql("SELECT markers.*, categories.category FROM categories LEFT JOIN markers ON markers.category_id = categories.id WHERE markers.category_id = categories.id")
            ->asArray()
            ->all();

        $xml = new XmlConstructor();
        $res=array();$k=0;
        foreach ($results AS $elements) {

            $elements=[
                'tag' => 'marker',
                'attributes' => [
                    'id' => $elements[id],
                    'name' => $elements[title],
                    'address' => 'Конюшенная',
                    'lat' => $elements[lat],
                    'lng' => $elements[lng],
                    'type' => $elements[category]
                ],
            ];

        }

        $result = [
            [
                'tag' => 'markers',
                'elements' => [
                    $elements
                ],
            ],
        ];
        return $xml->fromArray($result)->toOutput();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
JimmDiGreez, 2018-04-25
@isb97

I think something like this

foreach ($results as $elements) {
    $res[] = [
        'tag' => 'marker',
        'attributes' => [
            'id' => $elements['id'],
            'name' => $elements['title'],
            'address' => 'Конюшенная',
            'lat' => $elements['lat'],
            'lng' => $elements['lng'],
            'type' => $elements['category']
        ],
    ];
}

should help.

R
Rsa97, 2018-04-25
@Rsa97

$result = array_map(function($el) {
  return [
    'tag' => 'marker',
    'attributes' => [
      'id' => $el['id'],
      'name' => $el['title'],
      'address' => 'Конюшенная',
      'lat' => $el['lat'],
      'lng' => $el['lng'],
      'type' => $el['category']
    ]
  ];
}, $result);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question