Home > database >  Replace every string in multidimensional array if conditions matched
Replace every string in multidimensional array if conditions matched

Time:12-08

Ok so I have an array look like this,

Array
(
    [0] => Array
    (
        [0] => order_date.Year
        [1] => =
        [2] => 2024
    ),
    [1] => Array
    (
        [0] => order_date.Quarter
        [1] => =
        [2] => 1
    )
)

What I want to do is, in any element of this multidimensional array I want to replace any string that have a . with removing everything after .

So the new array should look like this,

Array
(
    [0] => Array
    (
        [0] => order_date
        [1] => =
        [2] => 2024
    ),
    [1] => Array
    (
        [0] => order_date
        [1] => =
        [2] => 1
    )
)

I have tried doing this,

foreach ($filter as $key => $value) {
    if(is_array($value)) {
        $variable = substr($value[0], 0, strpos($value[0], "."));
        $value[0] = $variable;
    }
}
print_r($filter);

I'm getting $value[0] as order_date but can't figure out how to assign it to $filter array without affecting other values in array;

CodePudding user response:

The $value variable is not linked with the original array in the foreach loop. You can make a reference to the original array by using ampersand "&"

foreach ($filter as $key => &$value) { ... }

Or you can use old school key nesting

$filter[$key][0] = $variable;

Please take a look here https://stackoverflow.com/a/10121508/9429832

CodePudding user response:

this will take off values after . in every element of any multidimensional array.

// $in is the source multidimensional array
array_walk_recursive ($in, function(&$item){
    if (!is_array($item)) {
        $item = preg_replace("/\.. $/", "", $item);
    }
});
  • Related