1

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

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.

有任何想法吗?

4

3 回答 3

1

这可能不是最有效的代码,但它可以满足您的需求。如果匹配中有多个条目$departments,它将采用第一个条目的索引。如果没有找到匹配项,它将分配 value 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;

于 2013-06-28T14:06:18.737 回答
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);
于 2013-06-28T14:32:56.280 回答
0

数组是通过索引值访问的,您需要遍历数组之一,然后您可以使用它的索引从其他数组中获取值

classes[$key]['department']==departments[$key]['code']
于 2013-06-28T13:55:20.100 回答