Search code examples
phparraysregexpreg-grep

preg_grep isn't working on multidimensional arrays


I've got an array of arrays called $jsonvpr. When trying to pull a preg_grep like preg_grep("/Jake.*.Peavy/i", $jsonvpr) it returns Notice: Array to string conversion in /var/www/html/crawlnew.php on line 310 a bunch of times (I supose once per entry on the array) and it don't return anything. I suspect the problem is that there are not just arrays, but arrays of arrays, and that's why it isn't worked as I wanted, but I don't know how should I do. Please, anyone can point me on the right direction?

A sample of how the array would be:

array(102) {
  [0]=>
  array(8) {
    [0]=>
    string(4) "Rank"
    [1]=>
    string(6) "Player"
    [2]=>
    string(13) "Games Started"
    [3]=>
    string(16) "Excellent Starts"
    [4]=>
    string(14) "Neutral Starts"
    [5]=>
    string(11) "Poor Starts"
    [6]=>
    string(12) "Volatility %"
    [7]=>
    string(3) "VPR"
  }
  [1]=>
  array(8) {
    [0]=>
    string(0) ""
    [1]=>
    string(73) "Clayton Kershaw"
    [2]=>
    string(0) ""
    [3]=>
    string(0) ""
    [4]=>
    string(0) ""
    [5]=>
    string(0) ""
    [6]=>
    string(0) ""
    [7]=>
    string(0) ""
  }
  [2]=>
  array(8) {
    [0]=>
    string(0) ""
    [1]=>
    string(73) "Felix Hernandez"
    [2]=>
    string(0) ""
    [3]=>
    string(0) ""
    [4]=>
    string(0) ""
    [5]=>
    string(0) ""
    [6]=>
    string(0) ""
    [7]=>
    string(0) ""
  }
  [...]

Solution

  • You could get all the names into an array first and preg_grep over that:

    $names = array_column($jsonvpr, 1);
    $foundElements = preg_grep("/Jake.*.Peavy/i", $names);
    

    Where the second argument of array_column, 1, is the index of the array element you want to match.