简体   繁体   中英

How extract arrays from array depend on values

My array is

    Array
(
    [Company] => Company
    [Model] =>Model
    [galleryID] => div
    [gallery] => Gallery #1
    [networking] => div
    [Type] =>Type
    [dualim] => DualIM
    [era] => div
    [mera] => Maera
    [meraos] => Meraeos
    [aper] => Aper
  )

How can I separate it to multiple array when value is "div" close the array and generate a new one to be like that

$Company =  Array
    (
        [Company] => Company
        [Model] =>Model
      );

$gallery = array(
        [galleryID] => div,
        [gallery] => Gallery #1

);

$networking = array(
        [networking] => div,
        [Type] =>Type,
        [dualim] => DualIM
);

$era = array(
        [era] => div,
        [mera] => Maera,
        [meraos] => Meraeos,
        [aper] => Aper,
);

I tried to using array_slice and many codes but not extract as I want How can I do that?

You can "split" your array by looping it and put the values in some other array like this:

$split = [];
$i = 0;
foreach($arr as $k => $v) {
    if ($v == 'div') {
        $i++;
    }
    $split[$i][$k] = $v;
}

print_r($split);

The result is an array. As for the variable names I couldn't find any logic behind it.

Just for fun, but makes no sense as a production code, I wrote this to fit better to your question, but as I said, makes no sense to use something like this:

$currentVar = '';
$i = 0;
foreach($arr as $k => $v) {
    if(!$currentVar) {
        $currentVar = $k;
        $$currentVar = [];
    }

    if ($v == 'div') {
        $currentVar = $k;
    }
    $$currentVar[$k] = $v;
}

var_dump($Company, $galleryID, $networking, $era);

This code will create a variable with the array key as each new value = div appears.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM