2016-02-12 4 views
0

Я переходящую несколько массивов, как это в PHPАльтернативные способы объединить два массива в PHP

//all the other stuff 
$sxml = simplexml_load_file($url); 
$json = json_encode($sxml); 
$jObj = json_decode($json); 

$new = new stdClass(); 
foreach ($jObj->entry as $entry) { 
    $s = new stdClass(); 
    $s->title = $entry->title; 
    $s->id = $entry->summary; 

$new->entries[] = $s; 
} 
$array1 = (array) $new; 

foreach ($jObj->entry as $entry) { 
     $urls[] = $entry->id; 
    } 

//$podcast_ids = []; 
//$info = []; 
foreach ($urls as $string) { 
    if (preg_match('/id(\d+)/', $string, $match)) { 
     $podcast_ids[] = $match[1]; 
    } 
} 
$json_array = json_decode(file_get_contents('https://itunes.apple.com/lookup?' . http_build_query(['id' => implode(',', $podcast_ids)]))); 

$info = new stdClass(); 
foreach ($json_array->results as $item) { 
    $t = new stdClass(); 
    $t->artistName = $item->artistName; 
    $t->feedUrl = $item->feedUrl; 
    $t->primaryGenreName = $item->primaryGenreName; 
    $t->artworkUrl60 = $item->artworkUrl60; 

    $info->entries[] = $t; 
} 
$array2 = (array) $info; 
$ab = array('a' => $array1, 'b' => $array2); 
print_r($ab); 

print_r($ab) дает мне что-то вроде этого:

Array 
(
    [a] => Array 
     (
      [entries] => Array 
       (
        [0] => stdClass Object 
         (
          [title] => Serial - This American Life 
          [id] => Serial is a podcast from the creators of This American Life, hosted by Sarah Koenig. Serial unfolds one story - a true story - over the course of a whole season. The show follows the plot and characters wherever they lead, through many surprising twists and turns. Sarah won't know what happens at the end of the story until she gets there, not long before you get there with her. Each week she'll bring you the latest chapter, so it's important to listen in, starting with Episode 1. New episodes are released on Thursday mornings. 
         ) 

        [1] => stdClass Object 
         (
          [title] => This American Life - This American Life 
          [id] => This American Life is a weekly public radio show, heard by 2.2 million people on more than 500 stations. Another 1.5 million people download the weekly podcast. It is hosted by Ira Glass, produced in collaboration with Chicago Public Media, delivered to stations by PRX The Public Radio Exchange, and has won all of the major broadcasting awards. 
         ) 

        [2] => stdClass Object 
         (
          [title] => Real Crime Profile - Real Crime Profile 
          [id] => Podcast talking about criminal cases and personality profiling. 
         ) 

       ) 

     ) 

    [b] => Array 
     (
      [entries] => Array 
       (
        [0] => stdClass Object 
         (
          [artistName] => This American Life 
          [feedUrl] => http://feeds.serialpodcast.org/serialpodcast 
          [primaryGenreName] => News & Politics 
          [artworkUrl60] => http://is2.mzstatic.com/image/thumb/Music69/v4/70/c9/71/70c97133-f3a8-738e-ea2c-27a6dc7d9731/source/60x60bb.jpg 
         ) 

        [1] => stdClass Object 
         (
          [artistName] => This American Life 
          [feedUrl] => http://feed.thisamericanlife.org/talpodcast 
          [primaryGenreName] => Personal Journals 
          [artworkUrl60] => http://is5.mzstatic.com/image/thumb/Music4/v4/1f/b8/0f/1fb80f69-bd94-8cad-0a2f-b082541d5f64/source/60x60bb.jpg 
         ) 

        [2] => stdClass Object 
         (
          [artistName] => Real Crime Profile 
          [feedUrl] => http://feeds.soundcloud.com/users/soundcloud:users:202076064/sounds.rss 
          [primaryGenreName] => History 
          [artworkUrl60] => http://is5.mzstatic.com/image/thumb/Music69/v4/e4/0d/1e/e40d1efe-f625-8d15-4e2e-706fecead1e8/source/60x60bb.jpg 
         ) 

       ) 

     ) 

) 

Это близко к тому, что я «Я ищу, но в идеале я хотел бы упростить это, тем более, что у меня нет никакого« дерева »a и b. Есть ли способ объединить их для создания одного массива вместо двух массивов в одном большом массиве?

EDIT

Это то, что я пытаюсь закончить с:

Array 
(
    [a] => Array 
     (
      [entries] => Array 
       (
        [0] => stdClass Object 
         (
          [title] => Serial - This American Life 
          [id] => Serial is a podcast from the creators of This American Life, hosted by Sarah Koenig. Serial unfolds one story - a true story - over the course of a whole season. The show follows the plot and characters wherever they lead, through many surprising twists and turns. Sarah won't know what happens at the end of the story until she gets there, not long before you get there with her. Each week she'll bring you the latest chapter, so it's important to listen in, starting with Episode 1. New episodes are released on Thursday mornings. 
          [artistName] => This American Life 
          [feedUrl] => http://feeds.serialpodcast.org/serialpodcast 
          [primaryGenreName] => News & Politics 
          [artworkUrl60] => http://is2.mzstatic.com/image/thumb/Music69/v4/70/c9/71/70c97133-f3a8-738e-ea2c-27a6dc7d9731/source/60x60bb.jpg 
         ) 

        [1] => stdClass Object 
         (
          [title] => This American Life - This American Life 
          [id] => This American Life is a weekly public radio show, heard by 2.2 million people on more than 500 stations. Another 1.5 million people download the weekly podcast. It is hosted by Ira Glass, produced in collaboration with Chicago Public Media, delivered to stations by PRX The Public Radio Exchange, and has won all of the major broadcasting awards. 
          [artistName] => This American Life 
          [feedUrl] => http://feed.thisamericanlife.org/talpodcast 
          [primaryGenreName] => Personal Journals 
          [artworkUrl60] => http://is5.mzstatic.com/image/thumb/Music4/v4/1f/b8/0f/1fb80f69-bd94-8cad-0a2f-b082541d5f64/source/60x60bb.jpg 
         ) 

        [2] => stdClass Object 
         (
          [title] => Real Crime Profile - Real Crime Profile 
          [id] => Podcast talking about criminal cases and personality profiling. 
          [artistName] => Real Crime Profile 
          [feedUrl] => http://feeds.soundcloud.com/users/soundcloud:users:202076064/sounds.rss 
          [primaryGenreName] => History 
          [artworkUrl60] => http://is5.mzstatic.com/image/thumb/Music69/v4/e4/0d/1e/e40d1efe-f625-8d15-4e2e-706fecead1e8/source/60x60bb.jpg 
         ) 

       ) 

     ) 

) 
+0

ли [array_merge] (https://secure.php.net/manual/de/function.array- merge.php) работают на вас? – k0pernikus

+2

'array_merge ($ ab ['a'], $ ab ['b'])'. У вас тоже есть абсурдно сверхкомплексный код. – ceejayoz

+0

Какова цель, которую вы пытаетесь выполнить? Вам нужен массив, и вы не запрашиваете массив из 'json_decode' ... Это кажется странным. Зачем нужны все эти «stdClass»? – Rein

ответ

1

Вы пробовали ПГПС array_merge?

$ab = array_merge($array1, $array2);

Вы можете также искать выход, как это:

$ab['entries'] = array_merge($array1['entries'], $array2['entries']);

+0

Первый вариант дает массив с '$ array1'. Он просто игнорирует '$ array2'. Второй объединяет их в один массив, но вместо того, чтобы иметь (например) 2 записи с 4 различными атрибутами, я получаю 4 записи с 2 атрибутами. То есть, они не сливаются вместе под одним и тем же ребенком. – jonmrich

+0

Thats, потому что я ответил до вашего редактирования, где вы действительно объяснили, что искали. – Todd

+0

Однако решение должно быть очевидно уже сейчас - вам просто нужно прокрутить внутренние части каждого массива 'entries' и объединить их содержимое в один отдельный массив. Я не собираюсь кодировать это для вас, посмотрите на комментарии по вашему вопросу - весь скрипт слишком громоздкий и запутанный, поэтому конкретное решение будет столь же запутанным. Сначала вы хотите реорганизовать эту процедуру для элегантности. – Todd

Смежные вопросы