用发生的数组替换所有出现的带索引的数组

时间:2013-06-28 13:49:36

标签: php

如果标题可能有点令人困惑,我很抱歉。但这是我的问题。我有以下数组称为类:

Array
(
    [0] => Array
        (
            [Name] => BE1A
            [Department] => Emmen
        )
     etc.

我有一个名为Departments的数组:

Array
(
    [0] => Array
        (
            [Name] => 3 Receptie Emmen
            [code] => Emmen
        )
    etc.

这些数组将导入我的数据库。但首先我需要将数组类中的值部门替换为classes.department == departments.code的行的索引。这样我就可以使用外键将类与部门链接起来。所以数组类应该是:

 Array
    (
        [0] => Array
            (
                [Name] => BE1A
                [Department] => 0
            )
         etc.

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

这可能不是最有效的代码,但它可以满足您的需求。如果$departments中的多个条目匹配,则它将获取第一个条目的索引。如果未找到匹配项,则会指定值NULL

$classes = array(
    array('Name' => 'BE1A', 'Department' => 'Emmen'),
    array('Name' => 'Something', 'Department' => 'Another'),
    array('Name' => 'Yet more', 'Department' => 'More'),
    array('Name' => 'Yet more again', 'Department' => 'Nothing')
);

$departments = array(
    array('Name' => '3 Receptie Emmen', 'code' => 'Emmen'),
    array('Name' => 'Something else', 'code' => 'Another'),
    array('Name' => 'More stuff', 'code' => 'More')
);


for($i=0; $i<count($classes); $i++) {
    $arr = array_filter($departments, function($dpt) use($classes, $i) {
        return ($dpt['code'] == $classes[$i]['Department']);
    });
    if(count($arr) > 0) {
        reset($arr);
        $classes[$i]['Department'] = key($arr);
    }
    else {
        $classes[$i]['Department'] = NULL;
    }
}

print_r($classes);

这将输出:

Array
(
    [0] => Array
        (
            [Name] => BE1A
            [Department] => 0
        )

    [1] => Array
        (
            [Name] => Something
            [Department] => 1
        )

    [2] => Array
        (
            [Name] => Yet more
            [Department] => 2
        )

    [3] => Array
        (
            [Name] => Yet more again
            [Department] => -1
        )

)

请注意,它使用array_filter的闭包,因此您需要至少使用php 5.3才能使用它。如果不这样做,则可以删除use($classes, $i)并在比较函数中添加global $classes, $i;

答案 1 :(得分:1)

迟到但你可以使用数组迭代器:

$classes = array(
  array('name' => 'Class1', 'department' => 'xyz'),
  array('name' => 'Class2', 'department' => 'foo'),
  array('name' => 'Class3', 'department' => 'bar'),
);

$departments = array(
  array('name' => 'Department1 name', 'code' => 'xyz'),
  array('name' => 'Department2 name', 'code' => 'foo'),
  array('name' => 'Department3 name', 'code' => 'bar'),  
);


$test = new ArrayIterator($classes);
while ($test->valid()) {
  $class = $test->current();
  foreach($departments as $department) {
    if ($class['department'] == $department['code']) {
      $key = $test->key();
      $classes[$key]['department'] = $key;
    }
  }
  $test->next();
}

print_r($classes);

答案 2 :(得分:0)

数组是通过索引值访问的,你需要迭代一个数组,然后你可以使用它的索引从其他数组中获取值

classes[$key]['department']==departments[$key]['code']