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;

3
  • 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? Commented Dec 8, 2021 at 5:28
  • @Cid I have submitted failed attempt. Sorry I just couldn't get it to working so I asked it here. Commented Dec 8, 2021 at 5: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 ? Commented Dec 8, 2021 at 5:48

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man. I haven't noticed it. Also didn't knew I can use reference in PHP too. Also can you up vote question?
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);
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.