2

I have an array like this:

$array = array(
    1234 => array(
        'title' => 'TitleA',
        'extra' => array(
            45 => 'SubA',
            54 => 'SubB',
        ),
        // More irrelevant data
    ),
    2345 => array(
        'title' => 'TitleB',
        'extra' => array(
            89 => 'SubC',
            98 => 'SubD',
        ),
        // More irrelevant data
    ),
);

I use:

$data = Set::classicExtract($array, '{\d+}.title');

To get an array like:

array(1234 => 'TitleA', 2345 => 'TitleB');

And:

$data = Set::classicExtract($array, '{\d+}.extra');

To get an array like:

array(
    1234 => array(
        45 => 'SubA',
        54 => 'SubB',
    ),
    2345 => array(
        89 => 'SubC',
        98 => 'SubD',
    ),
)

Now that the Set:: class has been deprecated for a while (since 2.2, we use 2.8) I would like to use the Hash:: class. But I can not find a function that will give me the same result. I've tried both Hash::extract() and Hash::combine() but without success.

Is this even possible with the Hash:: class?

wouter
  • 247
  • 2
  • 6
  • No, I'm trying to extract data from an array, using the Hash:: class in CakePHP 2.x. (documentation: http://book.cakephp.org/2.0/en/core-utility-libraries/hash.html) – wouter Jun 15 '16 at 12:10

1 Answers1

1

I was doing some similar work. Didn't found any other solution, just how to set key of array element to array itself. So just created helper to set _key to array:

array_walk($array, function(&$item, $key){
    $item['_key'] = $key;
});

Then everything becomes easy:

$result = Hash::combine($array, "{n}._key", "{n}.title");

and:

$result = Hash::combine($array, "{n}._key", "{n}.extra");
Bogdan Kuštan
  • 5,427
  • 1
  • 21
  • 30
  • This is a workable solution. Thank you for your answer. I wish CakePHP did not remove functionality with deprecating the Set:: class. – wouter Jun 15 '16 at 14:18