Создать массив с Set Extract в Cakephp с условиями - PullRequest
2 голосов
/ 21 июня 2010

У меня есть следующий массив:

Array
(
    [0] => Array
        (
            [id] => 4
            [rate] => 82.50
            [pounds] => 2
            [ounces] => 3
            [mailtype] => Package
            [country] => UNITED KINGDOM (GREAT BRITAIN)
            [svccommitments] => 1 - 3 business days
            [svcdescription] => Global Express Guaranteed (GXG)
            [maxdimensions] => Max. length 46", width 35", height 46" and max. length plus girth combined 108"
            [maxweight] =>30
        )

    [1] => Array
        (
            [id] => 6
            [rate] => 82.50
            [pounds] => 2
            [ounces] => 3
            [mailtype] => Package
            [country] => UNITED KINGDOM (GREAT BRITAIN)
            [svccommitments] => 1 - 3 business days
            [svcdescription] => Global Express Guaranteed Non-Document Rectangular
            [maxdimensions] => Max. length 46", width 35", height 46" and max. length plus girth combined 108"
            [maxweight] => 70
        )

И я хочу использовать инструменты Set: extract для CakePHP, чтобы отфильтровать этот массив по «максимальному весу», чтобы все элементы, у которых «максимальный вес» превышал X, получили массив из «rate» и «svcdescription». поля т.е.:

Array (
 [82.50] => Global Express Guaranteed Non-Document Rectangular
 ...
 etc
)

Это вообще возможно?

Ответы [ 3 ]

2 голосов
/ 12 ноября 2010

По моему мнению, чтобы получить наибольшее значение из Set::extract, было бы лучше начать с массива со структурой, более похожей на следующую (в противном случае я считаю, что вам придется запускать Set::extract внутри цикла):

$array = array(
    'Shipping' => array(
        array (
            "id" => 4,
            "rate" => 82.50,
            "pounds" => 2,
            "ounces" => 3,
            "mailtype" => "Package",
            "country" => "UNITED KINGDOM (GREAT BRITAIN)",
            "svccommitments" => "1 - 3 business days",
            "svcdescription" => "Global Express Guaranteed (GXG)",
            "maxdimensions" => 'Max. length 46", width 35", height 46" and max. length plus girth combined 108"',
            "maxweight" => 30
        ),
        array (
            "id" => 6,
            "rate" => 82.50,
            "pounds" => 2,
            "ounces" => 3,
            "mailtype" => "Package",
            "country" => "UNITED KINGDOM (GREAT BRITAIN)",
            "svccommitments" => "1 - 3 business days",
            "svcdescription" => "Global Express Guaranteed Non-Document Rectangular",
            "maxdimensions" => 'Max. length 46", width 35", height 46" and max. length plus girth combined 108"',
            "maxweight" => 70
        )
    )
);

Теперь вы можете использовать синтаксис пути для Set::extract() для извлечения элементов, максимальный вес которых превышает $x.

$extracted = Set::extract($array, '/Shipping[maxweight>'.$x.']');

С этими данными вы можетесоздайте массив, который вы ищете, используя ставки в качестве ключей и svcdescription в качестве значений, используя Set::combine().

$combined = Set::combine($extracted, '{n}.Shipping.rate', '{n}.Shipping.svcdescription');
0 голосов
/ 04 августа 2010

Почему вы не можете просто использовать цикл foreach для обработки массива.

$returnArray = array();

// Where $x is weight amount you're testing against
foreach ($yourData as $eachData) {
    if ($eachData['maxweight'] > $x) {
        $returnArray[$eachData['rate']] = $eachData['svcdescription'];
    }
}
0 голосов
/ 21 июня 2010

Я никогда не использовал это раньше, но спасибо, что побудили меня прочитать об этом.Вы пробовали использовать Set :: combin ()?

http://book.cakephp.org/view/662/combine

...