1

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;

  • What you've described is a task, not a problem. Not showing us your attempts to solve your tasks will lead to bad reactions. Would you please add your current attempts? – Cid Dec 08 '21 at 05:28
  • @Cid I have submitted failed attempt. Sorry I just couldn't get it to working so I asked it here. – Vivek Makwana Dec 08 '21 at 05:34
  • Not really understand what's your problem. You already change `$value[0]` so why not just simple assign to `$filter` by `$filter[$key] = $value` ? – Chen Kuan Hung Dec 08 '21 at 05:48

2 Answers2

2

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

0

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);
    }
});
diavolic
  • 722
  • 1
  • 4
  • 5