数组查找和替换其他数组

时间:2018-11-05 06:08:47

标签: php arrays

我有一个数组$data

Array
(
    [0] => Array
        (
            [quarter] => Q1
            [category] => DEODORANTS,FACE CARE
            [fund_type] => EOT
        )

    [1] => Array
        (
            [quarter] => Q2
            [category] => BODY CARE
            [fund_type] => A&P
        )

    [2] => Array
        (
            [quarter] => Q2
            [category] => ORAL CARE,NOCATEGORY
            [fund_type] => A&P
        )

)

和其他数组$categories

Array
(
    [0] => Array
        (
            [id] => 1
            [descriptions] => DEODORANTS
        )

    [1] => Array
        (
            [id] => 2
            [descriptions] => BODY CARE
        )

    [2] => Array
        (
            [id] => 3
            [descriptions] => FACE CARE
        )

    [3] => Array
        (
            [id] => 4
            [descriptions] => ORAL CARE
        )
)

我需要使用category中的$data来更改id$categories的值{{1}:

代码:

function lookup($data = array(), $categories = array())
{

  if(is_array($data))
  {

    foreach ($data as $k => $v)
    {

      $valCat = explode(',', $v['category']);

      if(!empty($valCat))
      {

        foreach ($valCat as $vc)
        {

          foreach ($categories as $c)
          {

            if($c['descriptions'] === $vc)
            {

              $CatID[] = $c['id'];

            }

          }

        }

      }

      $data[$k]['category'] = $CatID;

    }

    return $data;

  }

}

结果lookup($data, $categories)

Array
(
    [0] => Array
        (
            [quarter] => Q1
            [category] => Array
                (
                    [0] => 1
                    [1] => 3
                )

            [fund_type] => EOT
        )

    [1] => Array
        (
            [quarter] => Q2
            [category] => Array
                (
                    [0] => 1
                    [1] => 3
                    [2] => 2
                )

            [fund_type] => A&P
        )

    [2] => Array
        (
            [quarter] => Q2
                (
                    [0] => 1
                    [1] => 3
                    [2] => 2
                    [3] => 4
                )

            [fund_type] => A&P
        )

)

正确的结果应该是:

Array
(
    [0] => Array
        (
            [quarter] => Q1
            [category] => Array
                (
                    [0] => 1
                    [1] => 3
                )

            [fund_type] => EOT
        )

    [1] => Array
        (
            [quarter] => Q2
            [category] => Array
                (
                    [0] => 2
                )

            [fund_type] => A&P
        )

    [2] => Array
        (
            [quarter] => Q2
                (
                    [0] => 4
                )

            [fund_type] => A&P
        )

)

1 个答案:

答案 0 :(得分:1)

您没有重置$CatID的值。在此行之后

foreach ($data as $k => $v)
{

添加

    $CatID = array();