-2

Simple question in PHP, how to convert this below array to be string?

print_r($_POST['cb']);

//result
Array ( [0] => Array ( [id] => 1 [tipe] => create ) [1] => Array ( [id] => 1 [tipe] => delete ) [2] => Array ( [id] => 2 [tipe] => read ) [3] => Array ( [id] => 2 [tipe] => delete ) )

I tried this below code but not working:

echo implode(", ", $_POST['cb']);

//result
Array
(
[0] => Array
    (
        [id] => 1
        [tipe] => read
    )

[1] => Array
    (
        [id] => 1
        [tipe] => update
    )

[2] => Array
    (
        [id] => 2
        [tipe] => update
    )

)

What I want is to get id and tipe for each array.

halfer
  • 19,824
  • 17
  • 99
  • 186
HiDayurie Dave
  • 1,791
  • 2
  • 17
  • 45

2 Answers2

1

What you could is initialize an empty string and then loop through your arrays and add their elements to your initialized string like this :

$str = '';
foreach($arrs as $arr) { // $arrs is your $_POST['cb'] array
    foreach($arr as $item) {
        $str .= $item . ' ';
    }
}
echo $str;
Amr Aly
  • 3,871
  • 2
  • 16
  • 33
0
class StringBuilder {

    private $data;
    private $string;

    function __construct(array $data) {
        $this->data = $data;
    }

    public function get() {
        $this->parse();
        return $this->string;
    }

    private function parse() {
        foreach($this->data as $values) {
            $this->string .= $values['id'] . ' ' . $values['tipe'] . ' '; 
        }
        $this->string = trim($this->string);
    }
}

I think this would be the easiest way for you to achieve what you are attempting to do.

Available Methods:

  • __construct()
  • get()
Teddy Codes
  • 489
  • 4
  • 14