generate php array from database while loop - php

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
);

Related

Fill an array with multiple arrays with an foreach loop in php

I have a problem which I cant figure out. I have an array $navItems. In there I have multiple arrays with the items.
$navItems = array(
array(
"url" => 'index.php',
"title" => 'Home',
"id" => 1
),
array(
"url" => "pages/projects.php",
"title" => "Projects",
"id" => 2
),
array(
"url" => "pages/about.php",
"title" => "About",
"id" => 3
),
array(
"url" => "pages/contact.php",
"title" => "Contact",
"id" => 4
),
array(
"url" => "pages/login.php",
"title" => "Login",
"id" => 5
),
);
// Database conectie en query
$dbh = getDbConnection();
$sql = "SELECT * FROM pages";
$pages = $dbh->query($sql);
// Navitems
$navItems = array();
foreach($pages as $singe_page){
$page_title = $singe_page['title'];
$page_url =$singe_page['url'];
$page_id = $singe_page['id'];
$pagina = array(
'title' => $page_title,
'url' => $page_url,
'id' => $page_id
);
array_push($navItems, $pagina);
}
//This is the code on my array.php page. And it loads that in on the head.php
But now I want to add all the page arrays with an foreach loop. Because I have the pages saved in my database. And now I'm trying to pull the pages out my database and put them in the array.
But I just don't know anymore...
I just want for every record in my database it to throw that in an array and that array in the $navItems array.
Nevermind. When I was typing this I changed a little bit of code. And now it works. I added the array_push($navItems, $pagina) in the foreach loop. And it works.

Appending an array to a multi dimensional array fails silently PHP?

I am trying to append an array to another one in a multi dimensional array:
This is the multi dimensional array:
$info[] = array(
'key' => $row['id'],
'master' => array(
'name' => $row['master_name'],
"detail" => array()
)
);
I has a key which is the master id, and a master item which is an array with a name and another array with the detail (at the first time is empty).
But when I try to add to the $info['master']['detail'] array another array with a detail, like this:
$info['master']['detail'][] = array("name" => "A detail name",
"value" => "A detail value");
Nothing is added... How is that possible?
EDIT: the foreach loops that should add the details to the master:
foreach ($details as $detail)
{
$name = $detail['detail_name'];
$value = $detail['detail_value'];
if ($info['key'] == $detail['id']) {
$info['master']['detail'][] = array("name" => $name,
"value" => $value);
}
}
I'm not sure I understand but when I see your examples, I think it is a problem of index:
Try to replace
$info[] = array(
'key' => $row['id'],
'master' => array(
'name' => $row['master_name'],
"detail" => array()
)
);
$info['master']['detail'][] = array("name" => "A detail name",
"value" => "A detail value");
by
$info = array( 'key' => $row['id'],
'master' => array('name' => $row['master_name'],,
"detail" => array())
);
$info['master']['detail'] = array("name" => "A detail name",
"value" => "A detail value");
and to add a new value :
$info['master']['detail']['foo'] = "A detail foo";

Put nested array into one array

Suppose i have a array like this :
Array(
'1' => Array(
"ID" => 1,
"Name" => "name 1"
),
'2' => Array (
Array(
"ID" => 2,
"Name" => "name 2"
)
),
'3' => Array(
Array(
Array(
Array(
"ID" => 3,
"Name" => "name3"
)
)
),
'4' => Array (
Array {
"ID" => 4,
"Name" => "name 4"
),
Array(
"ID" => 5,
"Name" => "name 5"
),
Array(
"ID" => 6,
"Name" => "name 6"
)
);
number of sub-arrays is not ordered it may be 3, 4 or 5 etc...
and i wanted to get :
Array(
Array( "ID" => 1, "Name" => "name 1"),
Array( "ID" => 2, "Name" => "name 2"),
Array( "ID" => 3, "Name" => "name 3"),
Array( "ID" => 4, "Name" => "name 4"),
Array( "ID" => 5, "Name" => "name 5"),
Array( "ID" => 6, "Name" => "name 6"));
Is there an easy way to do this ?
EDIT :
Edited the above array to add :
'4' => Array (
Array {
"ID" => 4,
"Name" => "name 4"
),
Array(
"ID" => 5,
"Name" => "name 5"
),
Array(
"ID" => 6,
"Name" => "name 6"
)
);
which aren't nested but i still want them to be in my final array.
Thanks.
//Assuming your data is in $in
$out=array();
foreach($in as $k=>$v) {
while ((is_array($v)) && (isset($v[0]))) $v=$v[0];
//See below for next line
$out[]=$v;
}
print_r($out);
With the marked line being either $out[$k]=$v; or $out[]=$v; depending on wether you want to keep the 1st-level keys. In your desired output you do not ,so use the shown version
Edit
With you changed input array, you need to do something like
function addtoarray($inarray, &$outarray) {
foreach ($inarray as $i) {
if (!is_array($i)) continue;
if (isset($i['ID'])) $outarray[]=$i;
else addtoarray($i,$outarray);
}
}
$out=array();
addtoarray($in,$out);
print_r($out);
This was tested against your new input data
You could recurse through the array and check for the ID field.
function combine_array(array $src, array &$dest)
{
if( isset( $src['ID'] ) ) {
$dest[] = $src;
return;
}
foreach( $sub in $src ) {
combine_array( $sub, $dest );
}
}
Just wrote this off the top of my head, no testing, so it might have a few problems. But that's the basic idea.
This may work for you, assuming $array is the variable and php 5.3
//process
$array = array_map(function($block) {
$return = '';
foreach ($block as $sub) {
if (true === isset($sub['ID']) {
$return = $block;
break;
}
}
return $block;
}, $array);
array_filter($array); //remove empty elements
Wrote up a quick recursive function. You'll need to write any appropriate error handling and check the logic, since a discrepancy in your data could easily turn this into an infinite loop:
$output = array();
foreach ( $data as $d ) {
$output[] = loop_data( $d );
}
function loop_data( $data ) {
// Check if this is the right array
if( ! array_key_exists( "ID", $data ) ) {
// Go deeper
$data = loop_data( $data[0] );
}
return $data;
}

creating array dynamically

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

substr by using array as condition

I have a file contain text
ABBCDE1990-12-10JOBALPHABETabbcde1990-12-10jobalphabet
$field = array(
"fullname" => array("length"=5,"mandat"=>True),
"bithday" => array("length"=>10,"mandat"=>True)
"job" => array("length"=>3,"mandat"=>True),
"desc" => array("length"=>8,"mandat"=>false)
);
How can I get the array some thing like this:
$output = array(
//ABBCDE1990-12-10JOBALPHABET
0=>array(
"fullname" => "ABBCDE"
"bithday" => 1990-12-10
"job" => "JOB"
"desc"=> "ALPHABET"
)
//abbcde1990-12-10jobalphabet
1=>array(
"fullname" => "abbcde"
"bithday" => 1990-12-10
"job" => "job"
"desc"=> "alphabet"
)
);
I am tryin to buld a function
function toOutput($str,$filed){
$per_line = 27;//len of abbcde1990-12-10jobalphabet
$pos = 0;
while ($pos<strlen($str)){
$pos += 27;
//
}
}
$field = array(
"fullname" => array("length"=>6,"mandat"=>True),
"bithday" => array("length"=>10,"mandat"=>True),
"job" => array("length"=>3,"mandat"=>True),
"desc" => array("length"=>8,"mandat"=>false)
);
$string = 'ABBCDE1990-12-10JOBALPHABETabbcde1990-12-10jobalphabet';
$result = array();
$countString = strlen($string)/27;
$oldPos = 0;
for($i=0;$i<$countString;$i++) {
foreach($field as $k=>$v) {
$result[$i][$k] = substr($string,$oldPos,$v['length']);
$oldPos += $v['length'];
}
}
print_r($result);
You can see it up and running here: http://codepad.org/CEQNIPCg (version 0.3)
Based on that you can create a function so you can pass to it all $string that you have

Categories