简体   繁体   中英

How to split multidimensional array PHP

I have a multi dimensional array like

$array = array ( [0] => array ([0] => 'stack1', [1] => 'stack2'),
                 [1] => array ([0] => 'exchange1', [1] => 'exchange2'),
         [2] => array ([0] => 'overflow1', [1] => 'overflow2'),
         [3] => array ([0] => 'super1', [1] => 'super2')
     );

How can i split array having specific words like 'overflow', i have to shift it to two arrays like below. After that i want to loop.

$array1 = array ( [0] => array ([0] => 'stack1', [1] => 'stack2'),
                 [1] => array ([0] => 'exchange1', [1] => 'exchange2'),
          [2] => array ([0] => 'super1', [1] => 'super2')
        );

$array2 = array ( [0] => array ([0] => 'overflow1', [1] => 'overflow2') );

How can i achieve this using php

function array_find($needle, $haystack, $search_keys = false) {
    if(!is_array($haystack)) return false;
    foreach($haystack as $key=>$value) {
        $what = ($search_keys) ? $key : $value;
        if(strpos($what, $needle)!==false) return $key;
    }
    return false;
}

$word = 'overflow';
$c = count($array);
for ($i=0; $i<$c; $i++) {
    if (array_find($word, $array[$i])) {
        $array2[] = $array[$i];
    }
    else {
        $array1[] = $array[$i];
    }
}

array_find() is similar to array_search() , but it also works for partial matches.

$search = 'overflow'; // set the search phrase
foreach($array AS $sub) {
  $final = 1;
  foreach($sub AS $val) {
    if ( strpos($search,$val) ) { $final = 2; }
  }
  ${'array'.$final}[] = $sub;
}

I keep feeling like I'm copying Paul, second time my answer has so closely resembled his. I promise I'm not doing that on purpose. However this is different and hopefully this does the trick for you.

$array2 = array();
foreach( $array AS $key => $sub ) {
    foreach( $sub AS $item ) {
        if( strpos( $item, 'overflow' ) !== FALSE ) { $array2[ $key ] = ''; }
    }
}

$array2 = array_intersect_key( $array, $array2 );
$array1 = array_diff_key( $array, $array2 );

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