user1532468
user1532468

Reputation: 1753

Combine JSON array into single value

I am trying to concat several json key values so that I can return just a single value with all data. For example, In my code, I would like to combine address1, address2, address3 into Address. Is this possible. I have tried various methods of using the .= but nothing seems to work. Any heads up would be gratefully appreciated. Thanks

$query = "SELECT * FROM company_com";
$from = 0; 
$to = 30;
$query .= " LIMIT ".$from.",".$to;

$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $customers[] = array(
        'Address1' => $row['address1_com'],
        'Address2' => $row['address2_com'],
        'Address3' => $row['address3_com']
      );
}

echo json_encode($customers);

Upvotes: 1

Views: 87

Answers (2)

You can very well rewrite like this..

$customers = array(); $i=0; 
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $customers[$i]['Address1'] = $row['address1_com'];
    $customers[$i]['Address2'] = $row['address2_com'];
    $customers[$i]['Address3'] = $row['address3_com'];
    $i++;
}
echo json_encode($customers);

Changes done :

  • The $customers array declaration moved outside of the while
  • A flag $i=0; is set outside of the while.
  • The $customers array is made 2-Dimensional as you can see $i is passed as the key.
  • Finally, $i is incremented..

EDIT :

<?php
$customers = array(); $i=0;
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $customers[$i]['Address'] = $row['address1_com']." ".$row['address2_com']." ".$row['address3_com'];
    $i++;
}
echo json_encode($customers);

Upvotes: 3

Kayla
Kayla

Reputation: 485

I don't quite understand your problem.

Make sure that the column names are correct. address1_com, address2_com, etc.

Test the code by using print_r($row); on every iteration. print_r shows the contents of an array.

Also, what I would recommend you doing is, combining every address into an array. For example...

'Address' => array(
    $row['address1_com'],
    $row['address2_com'],
    $row['address3_com']
)

Upvotes: 0

Related Questions