creating array dynamically - php

I am trying to creates the array dynamically like below using php
$data = array(
array("date" => "1/2/2012", "sentstatus" => "0", "mobile" => "14578998"),
array("date" => "21/2/2012", "sentstatus" => "1", "mobile" => "14668998"),
array("date" => "1/5/2012", "sentstatus" => "1", "mobile" => "14598998"),
array("date" => "1/6/2012", "sentstatus" => "0", "mobile" => "14578748"),
);
Below is my PHP code that insert the sql server data into array but the problem is that it the array is formed of only last result set row of the database table. I am not getting the idea to insert all database table row into array as shown above:
$sql = "SELECT [start_date_time],[sent_status],[mobile_number] ,[play_file]
FROM [slice].[dbo].[tbl_message_detail] ";
$res = odbc_exec($con,$sql) or die(odbc_error());
$rows = odbc_num_rows($res);
while($row = odbc_fetch_array($res))
{
$data = array(
array("Date_Time" => $row['start_date_time'], "Send_Status" => $row['sent_status'], "Mobile_Number" => $row['mobile_number'], "play_file" => $row['play_file'])
);
}

You are getting only the last row because you are creating a new array with every iteration. Declare $data outside of the while loop.

try this code:
while($row = odbc_fetch_array($res))
{
$data[] = array("Date_Time" => $row['start_date_time'],
"Send_Status" => $row['sent_status'],
"Mobile_Number" => $row['mobile_number'],
"play_file" => $row['play_file']);
}

You're overwriting the $data variable at each round of the loop. This:
$data = array();
while($row = odbc_fetch_array($res))
{
$data[] = array("Date_Time" => $row['start_date_time'],
"Send_Status" => $row['sent_status'],
"Mobile_Number" => $row['mobile_number'],
"play_file" => $row['play_file']
);
}
should work as you need

Related

Pushing Into An Array MySQL Values

I am trying to push values from a sql query into an array using array_push.
Everything works fine except one field - "Beschreibung". It's a MySQL Text Field. When I put in the row "Beschreibung" the output from the PHP is completely empty.
Here is my code so far, any help is appreciated!
while ( $row = $result->fetch_assoc()) {
array_push($data, array(
"Beschreibung" => $row["Beschreibung"],
"id" => $row["id"],
"Titel_Veranstaltung" => $row["Titel_Veranstaltung"],
"Strasse" => $row['Strasse'],
"PLZ" => $row["PLZ"],
"Ort" => $row["Ort"],
"Bild" => $row["Bild"],
"Telefon" => $row["Telefon"],
"Datum" => $row["Datum"],
"Uhrzeit" => $row["Uhrzeit"],
"Latitude" => $row["latitude"],
"Longitude" => $row["longitude"],
"Teilnehmerzahl" => $row["Teilnehmerzahl"],
"Musikrichtung" => $row["Musikrichtung"],
"Art_Veranstaltung" => $row["Art_Veranstaltung"],
"Dauer_Veranstaltung" => $row["Dauer_Veranstaltung"]
));
}
echo json_encode($data);
Try this
$data = [];
while ( $row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode($data);

How do I compare these two Arrays for sameness?

I have an array consisting of seat number in the following format
<?php
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
?>
And also the retrieved data of reserved seats by users which comes in this format
<?php
$seat = array();
$sql = $db->query("SELECT booked_seat FROM mybooking where bus_id = '{$l}'");
$row = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach($row as $r){
$seat[] = $r['booked_seat'];
}
print_r($seat)
// Array ( [0] => A1 [1] => D2 )
?>
All I am trying to achieve is to disable the selected seats in a HTML select like I tried doing here
<?php
$keys = array_keys($seatnumbers);
$values = array_values($seatnumbers);
$skeys = array_keys($seat);
$val = array_values($seat);
for($i = 0; $i < 14; $i++ )
{
if($keys[$i] == $val[$i]){
echo "<option disabled>". $keys[$i]. "(Booked)</option>";
}else{
echo "<option value='".$keys[$i]."'>". $keys[$i]."-". $val[$i]. "(Available)</option>";
}
}
?>
But only the first option showed booked. How do compare for two arrays to disabled the reserved seats.
Here is the result of what I tried
Using prepared statements and also using PDO::FETCH_COLUMN to save having to process the result set from the SQL further. The code has comments to show how this is done.
You will have to change the output, but it matches what you have enough to modify it...
$query = "SELECT booked_seat FROM mybooking where bus_id = :busID";
$sql = $db->prepare($query);
$sql->execute(["busID" => $l]);
// Fetch an array with just the values of booked_seat
$seat=$sql->fetchAll(PDO::FETCH_COLUMN, 0);
// Flip array so the seat name becomes the key
$seat = array_flip($seat);
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
foreach ( $seatnumbers as $seatName => $number ) {
echo $seatName;
// If the key is set in the seat array, then it is booked
if ( isset($seat[$seatName]) ){
echo " Seat booked".PHP_EOL;
}
else {
echo " Seat not booked".PHP_EOL;
}
}
This is a typical task for using foreach
<html>
<head></head>
<body>
<?php
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
$seat = array(
"0" => "A1","1" => "D2",
"2" => "E1","3" => "E2","4" => "E3"
);
echo "<select>";
foreach ($seatnumbers as $ikey=>$ivalue)
{
if(in_array($ikey,$seat)){
echo "<option disabled>". $ikey. "(Booked)</option>";
}else{
echo "<option value='".$keys[$i]."'>". $ikey."-". $val[$i]. "(Available)</option>";
}
}
echo "</select>";
?>
</body>
</html>

generate php array from database while loop

I want to generate exactly same array from database data which I am getting from while loop which will be passed to some other function and it does not accept anything else.
When i pass this data manually it works so it should be exactly same.
$putArray7 =array
(
// "title" => "Test Product " ,
// "body_html" => "test description" ,
"images" => array
(
array(
"id" => "6800163209265",
"attachment" => "$attachment_base64",
),
array(
"id" => "6800163438641",
"attachment" => "$attachment_base64",
),
array(
"id" => "6800164880433",
"attachment" => "$attachment_base64",
),
)
);
What i tried:
$response99 = array();
$response_final = array();
// data from mysql starts here
while($row = mysqli_fetch_assoc($res))
{
$response99[] = ['id'=>$id_img_id .',',
'attachment'=>$attachment_base64];
}
Now tried to recreate whole array here:
// did not work
$response_final[] = ['title'=>"Test Product 53","body_html" => "test description" , 'images'=>$response99];
Tried this:
$response_final[] = ['title'=>"Test Product 53","body_html" => "test description" , 'images'=>[$response99]];
This one also did not work:
Tried several other ways. Any help will be great.
Want to generate exactly like $putArray7.
Do it like this:
$response99 = array();
$response_final = array();
while($row = mysqli_fetch_assoc($res)){
$a = array();
$a['id'] = $row['id'];
$a['attachment'] = $row['attachment'];
$response99[] = $a;
}
$response_final = array(
'title' => "Test Product 53",
'body_html' => "test description" ,
'images' => $response99
);

php while within array

I have to populate a json with PHP.
I have this structure:
$request = array(
"api_uid" => "000000",
"api_key" => "xxxxxx",
"lista_articoli" => array(
//loop
array(
"nome" => "Acconto",
"descrizione" => "Acconto per la festa del " .$datafesta,
"prezzo_lordo" => $importo,
"cod_iva" => 0
)
// end loop
I try to use while inside array, but it's an error:
while($row = $tipologia->fetch(PDO::FETCH_ASSOC)) {
array("nome" => $row['nome'],
"descrizione" => $row['desc'],
"prezzo_lordo" => $row['prezzo_lordo'],
"cod_iva" => 0
),
}
How can i loop my data in correct way inside array?
You can't loop inside array.You need to create array and assign value to them by keys in loop.Try like below :
while ($row = $tipologia->fetch(PDO::FETCH_ASSOC)) {
$request['lista_articoli'][] = [
'nome' => $row['nome'],
'descrizione' => $row['desc'],
'prezzo_lordo'] => $row['prezzo_lordo'],
'cod_iva' => 0,
];
}

Extracting from mulit-array and putting it into my own - php

I'm trying to extract data from a multidimensional array and then putting into one of my own so that I can load it into my database.
Source:
array( "ListOrdersResult" =>
array ( "Orders" =>
array( "Order" =>
array( [0] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
},
[1] => {
"Title" => $productTitle,
"customer_name" => $customerName,
"customer_id" => $customerId,
"random_info" => $randomInfo
}
)
)
)
To do this, I'm cycling through it like this - I have no issues with extracting data.
My code:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
$baseArray = $listOrderArray['ListOrdersResult']['Orders']['Order'][$i];
foreach($baseArray as $key => $value) {
if($key == "Title" || $key == "customer_id") {
//ADD TO multidimensional array
}
}
}
How I'm trying to structure it.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
The ultimate goal is to make it easier to load the information into the database by gathering the data by record and then loading it to the database rather than loading by creating an new record and then coming back and modifying that record. To me that seems like it would take more resources and has a higher chance of inconsistent data, but I'm new so I could be wrong.
Any help would be greatly appreciated.
You only have to unset keys you don't want:
$result = array_map(function ($i) {
unset($i['customer_name'], $i['random_info']);
return $i;
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
More about array_map
Or you also can select the keys you want:
$result = array_map(function ($i) {
return ['Title' => $i['Title'], 'customer_id' => $i['customer_id']];
}, $listOrderArray['ListOrdersResult']['Orders']['Order']);
About your code and question:
$count = count($listOrderArray['ListOrdersResult']['Orders']['Order']);
//Cycle through each Order to extract the data I want
for($i = 0; $count > $i; $i++) {
There's no reason to use a count and a for loop, use foreach.
array( [0] => {
array(
"Title" => $title,
"customer_id" => $customer_id
},
[1] => {
"Title" => $nextTitle,
"customer_id" => $next_customer_id
}
);
doesn't make sense, what are these curly brackets? You should write it like this if you want to be understood:
array(
[0] => array(
"Title" => "fakeTitle0",
"customer_id" => "fakeCustomerId0"
),
[1] => array(
"Title" => "fakeTitle1",
"customer_id" => "fakeCustomerId1"
)
);
You have this initial variable.
$listOrderArray = array(
"ListOrdersResult" => array(
"Orders" => array(
"Order" => array(
0 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
1 => array(
"Title" => "productTitle",
"customer_name" => "customerName",
"customer_id" => "customerId",
"random_info" => "randomInfo",
),
)
)
)
);
The only thing you should do is to remove the inner array from the three outer arrays.
Here is the solution:
$orders = $listOrderArray['ListOrdersResult']['Orders']['Order'];

Categories