使用in_array返回不正确的索引

时间:2016-01-07 20:32:59

标签: php arrays for-loop

for循环通过$ data_statuses数组,我希望它输出 epBwfEntry_update_submitted_epBwfNotify 索引的值,因为它存在于$ data中(复制下面的数组结构)。我正在循环通过该数组,并在使用$ data_statuses数组找到匹配后停止。

$data_statuses = array(
    'epBwfEntry_update_draft'                   =>  'draft',
    'epBwfEntry_create_draft'                   =>  'draft',
    'epBwfEntry_update_draft'                   =>  'draft',
    'epBwfEntry_update_submitted_epBwfNotify'   =>  'pending',
    'epBwfEntry_create_submitted_epBwfNotify'   =>  'pending',
    'epBwfDraft_create_submitted_epBwfNotify'   =>  'pending',
    'epBwfDraft_update_submitted_epBwfNotify'   =>  'pending',
);

foreach($data_statuses as $key => $value)
{
    if (in_array($key, $data))
    {
        print 'data: ' . $key . ': ' . $value . ' => ' . $data[$key]; 
        break;
    }
}

// index epBwfEntry_update_submitted_epBwfNotify exists in the $data array

// outputs: data: epBwfEntry_update_draft: draft =>

// expected output: epBwfEntry_update_submitted_epBwfNotify: pending => submitted

// $data array
Array
(
    [entry_id] => 3356
    [channel_id] => 1
    [autosave_entry_id] => 0
    [field_id_113] => YToxOntzOjE3OiJ0cmlnZ2VyX3JldmlzaW9ucyI7czoxOiIxIjt9
    [field_id_28] => 
    [field_id_103] => 
    [field_id_1] => 
    [field_id_79] => Yes
    [field_id_2] => 
    [field_id_3] => 
    [new_channel] => 1
    [epBwfEntry_update_submitted_epBwfNotify] => submitted
    [schedule_date_status] => no
    [draft_publish_date] => 01/19/2016
    [cp_call] => 1
    [revision_post] => Array
        (
            [entry_id] => 3356
            [channel_id] => 1
            [autosave_entry_id] => 0
            [filter] => 
            [structure__parent_id] => 2927
            [structure__template_id] => 146
            [structure__hidden] => n
            [title] => testtttt
            [structure__uri] => testtttt
            [url_title] => testtttt
            [expiration_date] => 
            [structure__listing_channel] => 0
            [field_id_113] => Array
                (
                    [trigger_revisions] => 1
                )

            [field_id_28] => Array
                (
                    [0] => 
                )

            [field_id_103] => 
            [field_id_1] => 
            [field_id_79] => Yes
            [field_id_2] => 
            [field_id_3] => 
            [entry_date] => 1452194340
            [new_channel] => 1
            [author] => 112
            [versioning_enabled] => y
            [epBwfEntry_update_submitted_epBwfNotify] => submitted
            [schedule_date_status] => no
            [draft_publish_date] => 01/19/2016
        )

    [options] => 
    [author] => 
)

1 个答案:

答案 0 :(得分:1)

in_array检查您正在搜索的数组中是否存在。您不是在搜索值而是搜索键,因此您需要(例如......):

if (array_key_exists($key, $data)) {
    ...

请注意,这不会搜索数组中值为数组的值中的键,但同样适用于in_array;两者都只搜索数组的第一级。