duanjia4969
2012-04-28 23:15
浏览 86
已采纳

PHP搜索数组使用通配符?

Assume that i have the following arrays containing:

Array (
     [0] => 099/3274-6974
     [1] => 099/12-365898
     [2] => 001/323-9139
     [3] => 002/3274-6974
     [4] => 000/3623-8888
     [5] => 001/323-9139
     [6] => www.somesite.com
)

Where:

  • Values that starts with 000/, 002/ and 001/ represents mobile (cell) phone numbers
  • Values that starts with 099/ represents telephone (fixed) numbers
  • Vales that starts with www. represents web sites

I need to convert given array into 3 new arrays, each containing proper information, like arrayTelephone, arrayMobile, arraySite.

Function in_array works only if i know whole value of key in the given array, which is not my case.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dongzhent208577 2012-04-28 23:20
    已采纳

    Loop through all the items and sort them into the appropriate arrays based on the first 4 characters.

    $arrayTelephone = array();
    $arrayMobile = array();
    $arraySite = array();
    
    foreach($data as $item) {
        switch(substr($item, 0, 4)) {
            case '000/':
            case '001/':
            case '002/':
                $arrayMobile[] = $item;
                break;
            case '099/':
                $arrayTelephone[] = $item;
                break;
            case 'www.':
                $arraySite[] = $item;
                break;
        }
    }
    
    已采纳该答案
    打赏 评论
  • drmeu26880 2012-04-28 23:18

    Create the three empty arrays, loop through the source array with foreach, inspect each value (regexp is nice for this) and add the items to their respective arrays.

    打赏 评论
  • doufendi9063 2012-04-28 23:20

    You can loop over the array and push the value to the correct new array based on your criteria. Example:

    <?php
    
    $fixed_array = array();
    
    foreach ($data_array as $data) {
        if (strpos($data, '099') === 0) {
            $fixed_array[] = $data;
        }
    
        if ....
    }
    
    打赏 评论
  • dsns47611 2012-04-28 23:30

    Yes i actually wrote the full code with preg_match but after reading some comments i accept that its better to show the way.

    You will create three different arrays named arrayTelephone, arrayMobile, arraySite.

    than you will search though your first array with foreach or for loop. Compare your current loop value with your criteria and push the value to one of the convenient new arrays (arrayTelephone, arrayMobile, arraySite) after pushing just continue your loop with "continue" statement.

    You can find the solution by looking add the Perfect PHP Guide

    打赏 评论

相关推荐 更多相似问题