Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP using array_replace with multidimensional array

Tags:

php

mysql

I am trying to build a game board 8x8 for a small game of battleship with game pieces in place (kind of like checkers) so i could move the pieces with MySQL the players can move freely in the board to go against each others battleships.

the pieces will be place in predetermined spaces while other space will be empty and be handle by mysql

$pieces = array(
          //battleship 1 player 1
          "b1" => '<img src="images/b1.jpg" width="100" height="100" alt="b1">',
          //battleship 2 player2
          "b2" => '<img src="images/b1.jpg" width="100" height="100" alt="b1">',
         );
              // 'es' represents empty squares
$board = array(
         array('b1','es','b1','es','b1','es','b1','es'),
         array('es','b1','es','b1','es','b1','es','b1'),
         array('b1','es','b1','es','b1','es','b1','es'),
         array('es','es','es','es','es','es','es','es'),
         array('es','es','es','es','es','es','es','es'),
         array('es','es','es','es','es','es','es','es'),
         array('b2','es','b2','es','b2','es','b2','es'),
         array('es','b2','es','b2','es','b2','es','b2'),
         array('b2','es','b2','es','b2','es','b2','es')
      );

I already have a loop to display the board what I'm asking is how do I place the ($piece -> $board) I know you can use the array_replace to place the elements of and array into another array, but I do not know how with multidimensional arrays.

I am also trying to use mysql for movement inside the board

like image 556
hgbso Avatar asked Dec 30 '25 11:12

hgbso


1 Answers

If you use PHP >= 5.3, you can use array_map:

$callback = function($value) use ($pieces) {
    if(array_key_exists($value, $pieces)) {
        return $pieces[$value];
    }
    return $value;
}

foreach($board as &$row) {
    $row = array_map($row, $callback);
}

If you use PHP < 5.3, you can use array_walk_recursive:

function map(&$value, $key, $map) {
    if(array_key_exists($value, $map)) {
        $value = $map[$value];
    }
}

array_walk_recursive($board, 'map', $pieces);

The not PHP 5.3 version would be shorter in both situations ;)

Update:

DEMO HERE :)

like image 191
Felix Kling Avatar answered Jan 01 '26 03:01

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!