Jon Erickson Jon Erickson - 3 months ago 24
PHP Question

Array in an array error

I have a slice of PHP code that's throwing an error;


Notice: Array to string conversion.


It is because for some reason
$deviceToken
is an array when it should be a string.

I don't why PHP thinks it is an array. When I print results array of my mysqli query, it shows an array in an array, and because of that, it thinks
$deviceToken
is an array. I only want one array,
$rows
and
$deviceToken
to be the value variables of the array. Because of this, later in the code where
$deviceToken
is read in the binary, its throwing another error because apparently its an array, not a string. See below for code:

// Create an array of units assigned to call
$unitsarray = explode(",", $units);

for ($i = 0; $i < count($unitsarray); $i++){

echo "Units row $i = $unitsarray[$i] <br />";

$result = $mysqli->query("SELECT devicetoken FROM `department devices` WHERE unit LIKE $unitsarray[$i]");

while($row = $result->fetch_assoc()) {
$rows[] = $row;
}

echo "ResultsArray = ";
print_r($rows);

// Loop APNS for each device token in $devicetoken array
foreach ($rows as $deviceToken)
{
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack("H*", $deviceToken) . pack('n', strlen($payload)) . $payload;

// Send it to the server
$result2 = fwrite($fp, $msg, strlen($msg));

// Create APNS operation output
if (!$result2)
echo 'Failed message'.PHP_EOL;
else
echo "<b>Successful message sent:</b>&nbsp;&nbsp; $call - $location - $station - $units to device(s):&nbsp;&nbsp;'$deviceToken </br>".PHP_EOL;
}
}


Results array output looks like this:

ResultsArray = Array (
[0] => Array (
[devicetoken] => 773f5436825a7115417d3d1e036da20e806efeef547b7c3fe4da724d97c01b30
)
)

Answer

$deviceToken is an array, you want the key devicetoken from that array, not the array itself.

foreach ($rows as $key => $row)
{    
    $deviceToken = $row['devicetoken'];  
    // Build the binary notification
    $msg = chr(0) . pack('n', 32) . pack("H*", $deviceToken) . pack('n', strlen($payload)) . $payload;

    // Send it to the server
    $result2 = fwrite($fp, $msg, strlen($msg));

    // Create APNS operation output
    if (!$result2)
        echo 'Failed message'.PHP_EOL;
    else
        echo "<b>Successful message sent:</b>&nbsp;&nbsp; $call - $location - $station - $units to device(s):&nbsp;&nbsp;'$deviceToken </br>".PHP_EOL;
}