Home > Software design >  how can I slice or splice array by value in php?
how can I slice or splice array by value in php?

Time:11-05

I'm recently learning PHP and making my own project. I usually array a lot in this app because most of the data I get is from open API. nevertheless, I faced a problem with dealing array yesterday and can't solve it yet due to my lack of skill and knowledge which is the reason I came here to ask.

What I'm curious about is this.

let's suppose an array like below

array(4){

  [0]=>
  array(3){
    ["a"] => 
    string(3) "abc"
    ["b"] => 
    string(3) "123"
    ["c"] => 
    string(3) "a15"

  }

  [1]=>
  array(3){
    ["a"] => 
    string(3) "def"
    ["b"] => 
    string(3) "456"
    ["c"] => 
    string(3) "5g2"
  }

  [2]=>
  array(3){
    ["a"] => 
    string(3) "ghi"
    ["b"] => 
    string(3) "123"
    ["c"] => 
    string(3) "79h"
  }


  [3]=>
  array(3){
    ["a"] => 
    string(3) "jkl"
    ["b"] => 
    string(3) "091"
    ["c"] => 
    string(3) "8b9"
  }




}

as you can see This is an array that has four arrays in it. and here are things I want to get from this array.

  1. a new array that has other arrays that the value of key "b" is "123"

so my expectation would be like below:

array(2){

[0]=>
array(3){
  ["a"] => 
  string(3) "abc"
  ["b"] => 
  string(3) "123"
  ["c"] => 
  string(3) "a15"

}


[1]=>
array(3){
  ["a"] => 
  string(3) "ghi"
  ["b"] => 
  string(3) "123"
  ["c"] => 
  string(3) "79h"
}

}

and the second thing I want to get is an also array that has remains of arrays

it would be like below:

array(2){

[0]=>
array(3){
  ["a"] => 
  string(3) "def"
  ["b"] => 
  string(3) "456"
  ["c"] => 
  string(3) "5g2"
}

[1]=>
array(3){
  ["a"] => 
  string(3) "jkl"
  ["b"] => 
  string(3) "091"
  ["c"] => 
  string(3) "8b9"
}

}

to get those arrays, I tried to use array_splice and array_slice but couldn't since their start point($offset) must be a number, not a conditional statement. (https://www.php.net/manual/en/function.array-splice.php) (https://www.php.net/manual/en/function.array-slice.php)

do you guys have any idea how to build this function? Share it with me please, if you have one

Thx for reading, your help will be appreciated.

CodePudding user response:

You need to use a condition inside foreach loop.

So assuming that your array with all items is $original:

$a = [];
$b = [];

foreach($original as $single){
 if($single['b'] == '123') {
  $a[] = $single;
 }else{
  $b[] = $single;
 }
}

This code will give you two new arrays in the end, $a and $b, one containing items that fulfil the condition and the other without it.

  • Related