S
S
sashafokin2015-01-13 11:46:57
PHP
sashafokin, 2015-01-13 11:46:57

How to trim values ​​in a multidimensional array?

Hey! I have an array like this:

Array
(
    [servers] => Array
        (
            [4] => Array
                (
                    [address] => xxxx
                    [protocol] => 48
                    [hostname] => xxxxx
                    [appid] => 10

                        (
                            [0] => Array
                                (
                                    [player_id] => 0
                                    [nick] => xxxxx
                                    [score] => 2
                                    [time_int] => 2680
                                    [time_gmt] => 44:40
                                )
                        )
                )
        )
)

And I need to trim the length of all values. Since the level and experience of using php is rather low, I end up with rather cumbersome nested loops, although I am sure that this can be solved within one to three lines.
I've used nested foreach constructs in my endeavors (up to three!), and I don't think this is the right way out. Please help. Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey, 2015-01-13
@sashafokin

Here in 3 lines

array_walk_recursive($your_array, function(&$value){
  $value = substr($value, 0, 3); // или что там вы подразумеваете под обрезанием
});

A
Alexey Nemiro, 2015-01-13
@AlekseyNemiro

I suspect that recursion is needed.
An example algorithm might look like this:

function Circumcision($arr, $size) // :-)
{
  $arr = array_slice($arr, 0, $size);
  foreach($arr as $item)
  {
     if(is_array($item))
     {
        $item = Circumcision($item, 1); // привык к ооп, если что я не виноват :)
     }
  }
  return $arr;
}

$input = array("a", "b", "c");
$result = Circumcision($input, 1);

I haven't been programming in PHP for a long time , I could forget the nuances and I'm not sure that the code will work. But the idea, I think, should be clear.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question