Как преобразовать массив объектов, содержащих значение, в массив, индексированный по этому значению? - PullRequest
0 голосов
/ 15 сентября 2011

У меня есть массив, структурированный так:

Array
(
    [0] => stdClass Object
    (
            [ID] => 277
            [post_author] => 1
            [post_date] => 2011-09-02 08:34:03
            [post_date_gmt] => 2011-09-02 08:34:03
            [post_content] => <div class="sol_topcont">
            [menu_order] => 103
            [post_type] => page
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
    )

    [1] => stdClass Object
    (
            [ID] => 275
            [post_author] => 1
            [post_date] => 2011-09-02 08:32:36
            [post_date_gmt] => 2011-09-02 08:32:36
            [post_content] => <div class="sol_topcont1">
            [menu_order] => 100
            [post_type] => page
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
    )

    [2] => stdClass Object
    (
            [ID] => 280
            [post_author] => 1
            [post_date] => 2011-09-02 08:35:24
            [post_date_gmt] => 2011-09-02 08:35:24
            [post_content] => <div class="sol_topcont">
            [menu_order] => 102
            [post_type] => page
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
    )

    [3] => stdClass Object
    (
            [ID] => 282
            [post_author] => 1
            [post_date] => 2011-09-02 08:36:31
            [post_date_gmt] => 2011-09-02 08:36:31
            [post_content] => <div class="sol_topcont">
            [menu_order] => 101
            [post_type] => page
            [post_mime_type] => 
            [comment_count] => 0
            [filter] => raw
    )

)

Мне нужно отсортировать этот массив, используя значение ключа ['menu_order'].Как я могу преобразовать вышеупомянутый массив в один как это:

Array
(

    [100] => stdClass Object
    (
        [ID] => 275
        [post_author] => 1
        [post_date] => 2011-09-02 08:32:36
        [post_date_gmt] => 2011-09-02 08:32:36
        [post_content] => <div class="sol_topcont1">
        [menu_order] => 100
        [post_type] => page
        [post_mime_type] => 
        [comment_count] => 0
        [filter] => raw
    )



    [101] => stdClass Object
    (
        [ID] => 282
        [post_author] => 1
        [post_date] => 2011-09-02 08:36:31
        [post_date_gmt] => 2011-09-02 08:36:31
        [post_content] => <div class="sol_topcont">
                    [menu_order] => 101
        [post_type] => page
        [post_mime_type] => 
        [comment_count] => 0
        [filter] => raw
    )
    [102] => stdClass Object
    (
        [ID] => 280
        [post_author] => 1
        [post_date] => 2011-09-02 08:35:24
        [post_date_gmt] => 2011-09-02 08:35:24
        [post_content] => <div class="sol_topcont">
                    [menu_order] => 102
        [post_type] => page
        [post_mime_type] => 
        [comment_count] => 0
        [filter] => raw
    )

    [103] => stdClass Object
    (
        [ID] => 277
        [post_author] => 1
        [post_date] => 2011-09-02 08:34:03
        [post_date_gmt] => 2011-09-02 08:34:03
        [post_content] => <div class="sol_topcont">
                    [menu_order] => 103
        [post_type] => page
        [post_mime_type] => 
        [comment_count] => 0
        [filter] => raw
    )
)

Ответы [ 4 ]

0 голосов
/ 15 сентября 2011

Также вы можете попробовать это:

$arr = array(
            array('menu_order' => 103, 'id' => 227),
            array('menu_order' => 101, 'id' => 221),
            array('menu_order' => 95, 'id' => 222),
            array('menu_order' => 105, 'id' => 223),
            array('menu_order' => 97, 'id' => 228),
            array('menu_order' => 99, 'id' => 229));

function cmpObj($obj1, $obj2)
{
    return $obj1->menu_order > $obj2->menu_order;
}

uasort($arr, 'cmpObj');

print_r($arr);

Демо

0 голосов
/ 15 сентября 2011

PHP имеет функцию usort, в которую вы можете передать пользовательский компаратор.Вам нужно создать функцию, имеющую два аргумента (в данном случае два ваших объекта), сравнить их и вернуть -1, 0 или 1 в зависимости от сравнения.

http://www.php.net/manual/en/function.usort.php

Пример

function cmp($a, $b) {
    if ($a->menu_order == $b->menu_order) {
        return 0;
    }
    return ($a->menu_order < $b->menu_order) ? -1 : 1;
}

usort($your_array, 'cmp');
0 голосов
/ 15 сентября 2011

Я получил ответ

    foreach($whyapptivo_sub_pages as $pages)
    {
            $key = $pages->menu_order;
            $final[$key] = $pages;
            ksort($final);
        }
   foreach($final as $page)
    {
             ........
          }
0 голосов
/ 15 сентября 2011
  1. создать новый пустой массив.
  2. пройти ваш исходный массив в цикле.
  3. получить ключ menu_order для текущего элемента в цикле.
  4. сохранить текущий элемент в новом массиве с menu_order в качестве ключа.
  5. после цикла уничтожить исходный массив.

Что-то вроде:

<?php

$newArray = array();
foreach($oldArray as $element)
{
    $menuKey = (string) $element->menu_order;
    $newArray[$menuKey] = $element;
}

$oldArray = null;
 // $newArray now has required data 

?>

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...