1

I have 2D arrays like this.

Array ( [0] => Array ( [0] => 1 [1] => 1 [2] => 0 [3] => 1)   [1] => Array ( [0] => 1 [1] => 0 [2] => 0 [3] => 0)   [2] => Array ( [0] => 1 [1] => 0 [2] => 0 [3] => 0

What I want is to print all this elements as a one string. That means, to print "110110001000"

I tried out something like this

for ($x = 0; $x < $this->smallersize; $x++) {
    for ($y = 0; $y < $this->smallersize; $y++) { 

         $myarray[$x][$y] = ($dct[$x][$y] >= $avg?"1":"0");    

        }
} 
return join('',$myarray);

What I want is to print "110110001000" My problem is when I tried out the above function it gives an

Error : "Array to string conversion" in line "return join('',$myarray);"

How to solve this?

Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
Tharu
  • 353
  • 1
  • 2
  • 11
  • Possibly this answers your question: http://stackoverflow.com/questions/8757773/convert-2d-array-to-a-string-using-php – dg131 Jul 04 '15 at 07:13

2 Answers2

2

You need to use implode twice as along with array_map

$array = Array(Array(1,1,0,1),Array(1,0,0,0),Array(1,0,0,0));
$result = array_map('implode',$array);
echo implode($result);//11011000100010

Using foreach as

foreach($array as $key => $value){
    foreach($value as $v){
        echo $v;
    }
}
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
  • This gives me something like this. Array ( [0] => 11010010 [1] => 10000011 [2] => 10001000 [3] => 00110100 [4] => 10011000 [5] => 01101001 [6] => 10010000 [7] => 10010011 ). I want to append all of this results. – Tharu Jul 04 '15 at 07:33
  • 1
    I am realy sorry, you said that to "use implode twice as along with array_map or for" I saw it now. Now it works. Thank you. – Tharu Jul 04 '15 at 07:39
  • 1
    @Uchiha you can use`echo implode($result);` as in `array_map` +1 – splash58 Jul 04 '15 at 12:02
1

As what i have understood: you need to append all the array's element sequentially.

$str = "";

for ($i = 0; $i<sizeOf($array); $i++)
{
    for ($j=0; $j<sizeOf($array[$i]); $j++)
    {
        $str .= $array[$i][$j];
    }
}

echo $str;
Danish Ahmed
  • 171
  • 1
  • 9
  • Thank you so much. This also works perfect. But @Uchiha has answered to the question first. So I selected that answer as the accepted one. But I selected your answer as useful. Thanks again – Tharu Jul 04 '15 at 07:42
  • no issue dear :) I am new to this so i was having some error "code is not formatted" which was not allowing me to submit, and i submitted a bit late :/ i am glad that i helped you :) – Danish Ahmed Jul 05 '15 at 08:31