PHP Create Associative Array from two arrays

时间:2016-07-11 19:26:30

标签: php arrays

I need to push a second array into the first array by matching "cat_id" in the first array to "parent_id" in the second array.

I have the first array - $categories:

[
  {
    "cat_id": "350",
    "parent_id": "0",
    "cat_name": "Category 1"
  }
]

And a second array - $topics:

[
  {
    "cat_id": "351",
    "parent_id": "350",
    "cat_name": "Topic 1",
  },
  {
    "cat_id": "352",
    "parent_id": "350",
    "cat_name": "Topic 2",
  }
]

And I want this:

[
  {
    "cat_id": "350",
    "parent_id": "0",
    "cat_name": "Category 1",
    "topics": [
        {
          "cat_id": "351",
          "parent_id": "350",
          "cat_name": "Topic 1",
        },
        {
          "cat_id": "352",
          "parent_id": "350",
          "cat_name": "Topic 2",
        }
    ]
  }
]

I'm thinking that an embeded foreach loop might be the answer, but still sifting through all of the PHP array functions to try an figure out if there is an existing function that just does this: http://php.net/manual/en/ref.array.php

1 个答案:

答案 0 :(得分:2)

The short answer is:

foreach ( $categories AS &$category ) {
  foreach ( $topics AS $topic ) {
    if ( $category[ 'cat_id' ] == $topic[ 'parent_id' ] ) {
      $category[ 'topics' ][] = $topic;
    }
  }
}

This full script should (I hope) demonstrate the behavior you're after.

<?php

$categories = array(
    [
      "cat_id" => "350",
      "parent_id" => "0",
      "cat_name" => "Category 1",
      "topics" => []
    ]
  );

$topics = array (
    [
      "cat_id" => "351",
      "parent_id" => "350",
      "cat_name" => "Category 1 Topic 1",
    ],
    [
      "cat_id" => "352",
      "parent_id" => "350",
      "cat_name" => "Category 1 Topic 2",
    ]
  );

foreach ( $categories AS &$category ) {
  foreach ( $topics AS $topic ) {
    if ( $category[ 'cat_id' ] == $topic[ 'parent_id' ] ) {
      $category[ 'topics' ][] = $topic;
    }
  }
}

echo '<pre>';
print_r( $categories );
echo '</pre>';

?>