我应该使用哪个PHP数组函数



我有两个数组:

Array
(
[0] => Array
    (
        [id] => 1
        [type] => field
        [remote_name] => Title
        [my_name] => title
        [default_value] => http%3A%2F%2Ftest.com
    )
[1] => Array
    (
        [id] => 2
        [type] => field
        [remote_name] => BookType
        [my_name] => book-type
        [default_value] => 
    )
[2] => Array
    (
        [id] => 3
        [type] => value
        [remote_name] => dvd-disc
        [my_name] => dvd
        [default_value] => 
    )
)

Array
(
[title] => Test
[book-type] => dvd
)

我需要取第二个数组中的每个键,将其与第一个数组中my_name的值匹配,并将其替换为第一个数组的相应remote_name的值,同时保留第二个阵列的值。

一定有一些c array zy函数可以提供帮助!

EDIT:在少数情况下,第二个数组的value需要替换为第一个数组remote_namevalue,其中第二个阵列的值与第一个阵列的my_name的值匹配。我怎样才能做到这一点?

EG:book-type => dvd应转变为BookType => dvd-disc

喜欢这样吗?:

$first = array(
    array(
        'id' => 1,
        'type' => 'field',
        'remote_name' => 'Title',
        'my_name' => 'title',
        'default_value' => 'http%3A%2F%2Ftest.com',
    ),
    array(
        'id' => 2,
        'type' => 'field',
        'remote_name' => 'BookType',
        'my_name' => 'book-type',
        'default_value' => '',
    ),
    array(
        'id' => 3,
        'type' => 'value',
        'remote_name' => 'dvd-disc',
        'my_name' => 'dvd',
        'default_value' => '',
    ),
);
$second = array(
    'title' => 'Test',
    'book-type' => 'dvd',
);
$map = array('fields' => array(), 'values' => array());
foreach ($first as $entry) {
    switch ($entry['type']) {
        case 'field':
            $map['fields'][$entry['my_name']] = $entry['remote_name'];
            break;
        case 'value':
            $map['values'][$entry['my_name']] = $entry['remote_name'];
            break;
    }
}
$new = array();
foreach ($second as $key => $val) {
    $new[isset($map['fields'][$key]) ? $map['fields'][$key] : $key] = isset($map['values'][$val]) ? $map['values'][$val] : $val;
}
print_r($new);

输出

Array
(
    [Title] => Test
    [BookType] => dvd-disc
)

解释

第一个循环收集字段和值的my_name/remote_name对,并使它们更易于访问。像这样:

Array
(
    [fields] => Array
        (
            [title] => Title
            [book-type] => BookType
        )
    [values] => Array
        (
            [dvd] => dvd-disc
        )
)

第二个循环将遍历CCD_ 10并使用其中的键/值对来填充CCD_。但这样做将检查$map中的键/值是否重复。

未在映射中找到的键或值将按原样使用。

foreach($arr1 as &$el) {
    $el['remote_name'] = $arr2[$el['my_name']];
}
unset($el);

我不知道这样一个c array zy函数,但我知道如何做到:

//$array1 is first array, $array2 is second array
foreach($array1 as $key => $value){
    if (isset($value['remote_name'], $value['my_name']) && $value['remote_name'] && $value['my_name']){
        $my_name = $value['my_name'];
        if (isset($array2[$my_name])) {
            $remote_name = $value['remote_name'];
            $array2[$remote_name] = $array2[$my_name];
            //cleanup
            unset($array2[$my_name]);
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新