通过PHP中的数组键的值对字典中的数组进行排序

时间:2014-03-21 21:34:35

标签: php ios json

这是一个两部分问题,但这里是我的PHP代码,我希望按升序(0,1,... 6)按天排序business_hours。这在PHP或iOS中是否更容易(这是为了集成到iOS应用程序中而编写的)?

另外,旁注,我的iOS开发人员说他在返回如下所示的位置数组字典时遇到了问题。他宁愿将位置作为带编号的数组([{},{},...]的JSON,而不是{},{},......),但问题是我可以& #39;在PHP中找到一种方法来满足此应用程序的要求。我特别需要使用数组键将营业时间添加到相应的位置。我正在连接三个表以获取营业时间和位置ID,以便营业时间的位置ID与该位置本身的位置ID匹配;这似乎是让两个数组加入JSON输出数组才能工作的唯一方法......你可以在下面看到,但如果我错了或者我的iOS开发人员更容易学习它,请告诉我如何迭代并返回带有键的多维关联数组的所有数组值。请指教!

if ($stmt = $dbh->prepare($query)) {
            // initialise an array for the results 
            $result = array();
            if ( $stmt->execute(array($lat,$lat,$lng,$rest_price,$eat_in,$take_out,$delivery)) ) {
                        // loop through all values
                while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) {
                    // Have we seen this menu before? If not, add it to the array
                    if ( !isset($result['locations'][$row['rest_id']]) ) {
                        $result['locations'][$row['rest_id']] = array(
                            'rest_id' => $row['rest_id'],
                            'user_id' => $row['user_id'],
                            'rest_name' => $row['rest_name'],
                            'lat' => $row['lat'],
                            'lng' => $row['lng'],
                            'rest_price' => $row['rest_price'],
                            'rest_rating' => $row['rest_rating'],
                            'rest_genre' => $row['rest_genre'],
                            'eat_in' => $row['eat_in'],
                            'take_out' => $row['take_out'],
                            'delivery' => $row['delivery'],
                            'rest_img' => $row['rest_img'],
                            'user_img' => $row['user_img'],
                            'business_hours' => array()
                        );
                    }
                    // Add the ingredient.
                    // remove all NULL, FALSE and Empty Strings but leave 0 (zero) values
                    $result['locations'][$row['rest_id']]['business_hours'][] = array_filter(array(
                        'day' => $row['day'],
                        'open_time' => $row['open_time'],
                        'close_time' => $row['close_time']
                    ), 'strlen');
                }

                // print results if not null
                if( $result != null ) {       
                    // print success. no error.
                    $result['error'] .= '';     
                    echo json_encode($result);
                    //print_r($result);
                } else {
                    echo json_encode(array('error' => 'No locations exist in your area'));
                }

阵列

(
[locations] => Array
    (
        [67] => Array
            (
                [rest_id] => 67
                [user_id] => 19
                [rest_name] => The Ninja
                [lat] => 34.1516
                [lng] => -106.685591
                [rest_price] => 2
                [rest_rating] => 3.5
                [rest_genre] => Japanese
                [eat_in] => 1
                [take_out] => 1
                [delivery] => 1
                [rest_img] => 88/image11.png
                [user_img] => image595.png
                [business_hours] => Array
                    (
                        [0] => Array
                            (
                                [day] => 4
                                [open_time] => 09:00:00
                                [close_time] => 16:30:00
                            )

                        [1] => Array
                            (
                                [day] => 1
                                [open_time] => 10:00:00
                                [close_time] => 17:00:00
                            )

                        [2] => Array
                            (
                                [day] => 6
                                [open_time] => 12:00:00
                                [close_time] => 18:00:00
                            )

                        [3] => Array
                            (
                                [day] => 3
                                [open_time] => 10:00:00
                                [close_time] => 17:00:00
                            )

                        [4] => Array
                            (
                                [day] => 0
                                [open_time] => 00:00:00
                                [close_time] => 00:00:00
                            )

                        [5] => Array
                            (
                                [day] => 5
                                [open_time] => 10:00:00
                                [close_time] => 17:00:00
                            )

                        [6] => Array
                            (
                                [day] => 2
                                [open_time] => 10:00:00
                                [close_time] => 17:00:00
                            )

                    )

            )// more arrays occur after this...

    )

[error] => 
)

JSON

{"locations":{"67":{"rest_id":"67","user_id":"19","rest_name":"The Ninja","lat":"","lng":"","rest_price":"2","rest_rating":"3.5","rest_genre":"Japanese","eat_in":"1","take_out":"1","delivery":"1","rest_img":"","user_img":"","business_hours":[{"day":"6","open_time":"12:00:00","close_time":"18:00:00"},{"day":"3","open_time":"10:00:00","close_time":"17:00:00"},{"day":"0","open_time":"00:00:00","close_time":"00:00:00"},{"day":"5","open_time":"10:00:00","close_time":"17:00:00"},{"day":"2","open_time":"10:00:00","close_time":"17:00:00"},{"day":"4","open_time":"09:00:00","close_time":"16:30:00"},{"day":"1","open_time":"10:00:00","close_time":"17:00:00"}]},{},...},"error":""}

1 个答案:

答案 0 :(得分:2)

嗯,这花了很长时间(部分是因为json字符串无效,因为它中有...,但是w / e)。

您的开发人员更喜欢像{"locations":[{},{},...],"error":""}这样的字典数组而不是像这样的字典词典 {"locations":{"67":{},"89":{},...} ,"error":""}因为字典数组非常适合iOS表格视图范例。但是,将字典词典转换为字典数组只需要一行代码,例如。

NSArray *locationAllValues = [locationDictionary allValues];

所以唯一的问题就是表现。您是否强制服务器执行更多工作以生成首选格式,或者让移动设备执行某些工作?

在解析JSON数据时,我建议使用NSJSONReadingMutableContainers选项,以便数组和字典是可变的。这样可以更轻松地对day数组进行排序。是的,在iOS中对数组进行排序很容易。这是一整套代码,可以从输入JSON创建一个字典数组。代码的输入是NSData对象,其中包含从网络下载的JSON字符串。字典数组按rest_id排序,在每个字典中,business_hours数组按day排序。

请注意,除了在调用nil后检查JSONObjectWithData之外,代码没有错误检查。这只是概念的证明,而不是生产代码。使用风险自负。

- (NSArray *)parseAndSortJsonResponse:(NSData *)data
{
    NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    if ( !jsonData )
    {
        NSLog( @"Invalid JSON string" );
        return( nil );
    }

    NSMutableDictionary *locationDictionary = jsonData[@"locations"];
    NSArray *locationAllValues = [locationDictionary allValues];

    NSArray *locationsArray = [locationAllValues sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
    {
        NSDictionary *d1 = obj1;
        NSDictionary *d2 = obj2;

        int v1 = [d1[@"rest_id"] intValue];
        int v2 = [d2[@"rest_id"] intValue];

        if ( v1 < v2 )
            return( NSOrderedAscending );
        else if ( v1 > v2 )
            return( NSOrderedDescending );
        else
            return( NSOrderedSame );
    }];

    for ( NSMutableDictionary *location in locationsArray )
    {
        NSArray *array = location[@"business_hours"];
        NSArray *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2)
        {
            NSDictionary *d1 = obj1;
            NSDictionary *d2 = obj2;

            int v1 = [d1[@"day"] intValue];
            int v2 = [d2[@"day"] intValue];

            if ( v1 < v2 )
                return( NSOrderedAscending );
            else if ( v1 > v2 )
                return( NSOrderedDescending );
            else
                return( NSOrderedSame );
        }];
        [location setObject:sorted forKey:@"business_hours"];
    }

    NSLog( @"%@", locationsArray );

    return( locationsArray );
}