PHP: Display data from Array - php

I working on a program and coming up with some annoying issue. I am trying to display data from an array. I copied the format from another array I setup and it works perfect. The only difference is I am gathering a lot more data...
Calling the function:
$data1 = display_orders($_SESSION['user_id'], $limit, 'fName', 'lName', 'VendorName', 'DateRequested', 'Shipping', 'VendorNumber', 'VendorFax', 'VendorAddress', 'VendorCity', 'VendorState', 'VendorZip', 'EquipmentConsumable', 'GasType', 'GasLocation', 'UNMTag', 'EquipmentLocation', 'index', 'totalcost', 'Approved', 'Shipped');
The Function itself
<?php
function display_orders($user_id, $limit)
{
$data = array();
$user_id = (int)$user_id;
$limit = (int)$limit;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
// print_r($func_get_args);
if ($func_num_args > 1)
{
unset($func_get_args[0]);
unset($func_get_args[1]);
$fields = '`' . implode('`, `', $func_get_args) . '`';
for($x = 0; $x < $limit; $x++)
{
$data[] = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` , `vendor` WHERE $user_id = users.id AND $user_id = vendor.user_id ORDER BY vendor.DateRequested DESC"));
}
return $data;
}
}
?>
So now i try to echo the data out:
echo $data1['VendorName'];
I get no output.
If I do the following:
print_r ($data1);
I get output!
Array ( [0] => Array ( [fName] => admin [lName] => test [VendorName] => Newegg [DateRequested] => 2013-09-19 [Shipping] => Standard [VendorNumber] => NA [VendorFax] => NA [VendorAddress] => NA [VendorCity] => NA [VendorState] => NA [VendorZip] => 00000 [EquipmentConsumable] => Equipment [GasType] => [GasLocation] => [UNMTag] => 0 [EquipmentLocation] => Computer Lab [index] => 0 [totalcost] => 39.99 [Approved] => 0 [Shipped] => 0 ) )
But if i try to add a field name No data....
Any help and I would be grateful!

As you see, $data1 is Array([0] => Array(...)), so you'll need to call
echo $data1[0]['VendorName'];
This is because you are assigning data as $data[] = mysql_fetch_assoc(...).

echo $data1[0]['VendorName'];
I suggest when using print_r you first echo <PRE> as it will help you to see the true structure of the array easier. In this case, the location of VendorName is one layer deeper than you are echoing.

You forgot the index [0]:
echo $data1[0]['VendorName'];

Related

Convert array to query php

so, i have this
Array
(
[ModuleCode] => Array
(
[0] => MD001
[1] => MD002
[2] => MD004
[3] => MD005
)
[MD001] => Array
(
[insert] => on
[edit] => on
[delete] => on
)
[MD002] => Array
(
[insert] => on
[edit] => on
[delete] => on
)
[MD005] => Array
(
[insert] => on
[edit] => on
[delete] => on
[access_edit] => on
)
)
as you can see there are an array with ModuleCode as key.
After some try i can get this
MD001
insert => 1
edit => 1
delete => 1
access_edit => 0
MD002
insert => 1
edit => 1
delete => 1
access_edit => 0
MD004
insert => 0
edit => 0
delete => 0
access_edit => 0
MD005
insert => 1
edit => 1
delete => 1
access_edit => 1
with this script
$dataModul = $this->input->post('ModuleCode');
$field = array ("insert","edit","delete","access_edit");
for($x=0;$x<count($dataModul);$x++){
echo "<pre>".$dataModul[$x] . "<br>";
for($a=0;$a<count($field);$a++){
$subcheck = (isset($this->input->post($dataModul[$x])[$field[$a]])) ? 1 : 0;
echo $field[$a]. " => " . $subcheck . "<br>" ;
}
echo "<pre>";
}
Ok, here is what i want to achieve . from this part (for an example)
MD001
insert => 1
edit => 1
delete => 1
access_edit => 0
i want to make something like this
Update TableName set insert = 1, edit = 1, delete = 1 , access_edit = 0 where ModuleCode = 'MD001'
How can i achieve that ? thanks in advance
You can try this code:
You can call use the function as echo generate_query_string('MD004', $modules); where the first parameter is the module code and the second the whole array.
<?php
function generate_query_string( $module, $module_arr ) {
if( !isset( $module_arr[$module] ) ) { return false; } // return false if module does not exist
// set default values
$defaults = array(
'insert' => 0,
'edit' => 0,
'delete' => 0,
'access_edit' => 0
);
$settings = array_merge( $defaults, $module_arr[$module] ); // merge default values and the actual values
$settings = array_filter( $settings ); // remove items with 0 value since we don't need to include them on the query string
// render the query string values
$values = [];
foreach ($settings as $key => $value) {
$value = ( $value == 'on' )? 1 : 0;
$values[] = $key. ' = '. $value;
}
$values = implode(', ', $values);
return 'Update TableName set '. $values .' where ModuleCode = '. $module;
}
?>
I found the solustion. Here is what i do
First. i add a custom function ( ref : https://stackoverflow.com/a/42052020/6354277 )
function custom_function($input_array)
{
$output_array = array();
for ($i = 0; $i < count($input_array); $i++) {
for ($j = 0; $j < count($input_array[$i]); $j++) {
$output_array[key($input_array[$i])] = $input_array[$i][key($input_array[$i])];
}
}
return $output_array;
}
then i change my code to this.
function updateaccess(){
$dataModul = $this->input->post('ModuleCode');
$field = array ("insert","edit","delete","access_edit");
for($x=0;$x<count($dataModul);$x++){
for($a=0;$a<count($field);$a++){
$subcheck[$a] = (isset($this->input->post($dataModul[$x])[$field[$a]])) ? 1 : 0;
$mynewarray[$dataModul[$x]][] = array($field[$a] => $subcheck[$a]);
}
foreach ($mynewarray as $key => $value) {
$forSave[$dataModul[$x]] = $this->custom_function($value);
}
}
foreach ($forSave as $key2 => $values2) {
$this->mainmodel->updateRow(array("ModuleCode" => $key2),"user_modules", $values2 );
}
}

Php array and json

help me to convert the following array in to json.
I tried to convert the array.
Array
(
[0] => Array
(
[c_code] => 200001
[itemname] => 303 10CAP
[c_pack_code] => PK0075
[c_web_img_link] =>
)
[1] => Array
(
[c_code] => 200005
[itemname] => 3P 4TAB
[c_pack_code] =>
[c_web_img_link] =>
)
)
current result for the following code is
public function searchOrder($idx, $data) {
if (!empty($data)) {
$result = OrderbukModel::func_get_searchlist($idx,$data);
if (!empty($result)) {
$resultArray[] = $result;
print_r(json_encode($result));
} else {
$resultArray[$idx] = ["Mysql returns empty result !"];
print_r(json_encode($resultArray));
exit;
}
}
}
now i got the result is like
[{"c_code":"200001","itemname":"303 10CAP","c_pack_code":"PK0075","c_web_img_link":""},{"c_code":"200005","itemname":"3P 4TAB","c_pack_code":"","c_web_img_link":""}]
But I need the result as follows
[{"c_code":"2000001","c_code":"200005"},
{"itemname":"303 10CAP","itemname":"3P 4TAB"},
{"c_pack_code":"PK0075","c_pack_code":""},
{"c_web_img_link":"","c_web_img_link":""}]
Example of how you can you make the json from array. Collect the data in two different array and after loop marge them and store the result in another array after that encode them.
Note: Your desired JSON is not a valid format, you can't use same index
for two data.
Online Example: https://3v4l.org/kdPDI
$arr = array(
array(
'c_code' => '200001',
'itemname' => '303 10CAP',
'c_pack_code' => 'PK0075',
'c_web_img_link' => ''
),
array(
'c_code' => '200005',
'itemname' => '3P 4TAB',
'c_pack_code' => '',
'c_web_img_link' => ''
)
);
$res1 = array();
$res2 = array();
foreach($arr as $val){
$res1['c_code'][] = $val['c_code'];
$res1['itemname'][] = $val['itemname'];
$res2['c_pack_code'][] = $val['c_pack_code'];
$res2['c_web_img_link'][] = $val['c_web_img_link'];
}
$out = array(array_merge($res1, $res2));
echo json_encode($out);

Using a loop to perform multiple SQL inserts using Codeigniter/Activerecord

I have an array that looking like this:
Array
(
[currency] => GBP
[shipping] => 3.5
[tax] => 0
[taxRate] => 0
[itemCount] => 3
[item_name_1] => Proletarian Sparrow
[item_quantity_1] => 2
[item_price_1] => 75
[item_name_2] => Guillemot Colony
[item_quantity_2] => 5
[item_price_2] => 20
[item_name_3] => Dandelion Clock
[item_quantity_3] => 2
[item_price_3] => 50
)
I'm trying to use a loop to extract the individual item details and insert a row in a database for each one. I'm using Codeigniter.
My model looks like this:
public function set_order($cust_id, $order_data)
{
// Breaks up order information and creates a new row in the pn_orders tables for each item
// Get the last row in the orders table so we can work out the next order_id
$this->db->order_by('order_id', 'desc');
$this->db->limit(1);
$query = $this->db->get('pn_orders');
$row = $query->row_array();
// If the resulting array is empty, there are no orders so we can set the order_id to 1. If there is already an order_id, just add 1 to it.
if (empty($row)) {
$order_id = 1;
} else {
$order_id = $row['order_id'] + 1;
}
//echo "<pre>";
//print_r($order_data);
//echo "</pre>";
// The delivery message input has a placeholder. if the user's input is different to this, assign it to $delivery_message.
if ($this->input->post('delivery_message') == "e.g. if out, leave in porch") {
$delivery_message = NULL;
} else {
$delivery_message = $this->input->post('delivery_message');
}
// Set today's date for insertion into the DB
$date = date('Y-m-d');
// The order information is clumped together in a single array. We have to split out single items by looping through the array before inserting them into the DB.
for ($i = 1; $i <= $order_data['itemCount']; $i++) {
$item = array(
'order_id' => $order_id,
'cust_id' => $cust_id,
'date_ordered' => $date,
'item_name' => $order_data["item_name_{$i}"],
'item_quantity' => $order_data["item_quantity_{$i}"],
'item_price' => $order_data["item_price_{$i}"],
'payment_method' => $_POST['payment_method'],
'delivery_message' => $delivery_message
);
$this->db->insert('pn_orders', $item);
}
}
Everything seems to be in place, however, only 1 row is ever inserted and I can't work out why. It seems very simple.
Is it something to do with the Activerecord pattern?
Thanks.
First print out the array to see if the array structure is correct or not. If its Okay then just use insert_batch like this:
for ($i = 1; $i <= $order_data['itemCount']; $i++) {
$items[] = array(
'order_id' => $order_id,
'cust_id' => $cust_id,
'date_ordered' => $date,
'item_name' => $order_data["item_name_{$i}"],
'item_quantity' => $order_data["item_quantity_{$i}"],
'item_price' => $order_data["item_price_{$i}"],
'payment_method' => $_POST['payment_method'],
'delivery_message' => $delivery_message
);
}
//echo "<pre>";print_r($item);echo "</pre>";die; uncomment to see the array structure
$this->db->insert_batch('pn_orders', $items);

Create array of hierarchical directories in PHP

I have the following code (I know that this code is not optimized but it's not for discussion):
function select_categories($cat_id)
{
$this->db = ORM::factory('category')
->where('parent', '=', $cat_id)
->find_all();
foreach ($this->db as $num => $category)
{
if($category->parent == 0)
{
$this->tmp[$category->parent][$category->id] = array();
}
else {
$this->tmp[$category->parent][$category->id] = array();
}
$this->select_categories($category->id);
}
return $this->tmp;
}
Function returns this array:
array(3) (
0 => array(2) (
1 => array(0)
2 => array(0)
)
2 => array(1) (
3 => array(0)
)
3 => array(2) (
4 => array(0)
5 => array(0)
)
)
But how should I change the code
else {
$this->tmp[$category->parent][$category->id] = array();
// ^^^^^^^^^^^^^^^^^^^^^^ (this bit)
}
To merge array[3] to array[2][3] for example (because array[3] is a subdirectory of array[2] and array[2] is a subdirectory of array[0][2]), so, I need to make this (when I don't know the level of subdirectories):
array (
0 => array (
1 => array
2 => array (
3 => array (
4 => array
5 => array
)
)
)
)
A long time ago I wrote some code to do this in PHP. It takes a list of entities (in your case, categories) and returns a structure where those entities are arranged in a tree. However, it uses associative arrays instead of objects; it assumes that the “parent” ID is stored in one of the associative array entries. I’m sure that you can adapt this to your needs.
function make_tree_structure ($nontree, $parent_field)
{
$parent_to_children = array();
$root_elements = array();
foreach ($nontree as $id => $elem) {
if (array_key_exists ($elem[$parent_field], $nontree))
$parent_to_children [ $elem[$parent_field] ][] = $id;
else
$root_elements[] = $id;
}
$result = array();
while (count ($root_elements)) {
$id = array_shift ($root_elements);
$result [ $id ] = make_tree_structure_recurse ($id, $parent_to_children, $nontree);
}
return $result;
}
function make_tree_structure_recurse ($id, &$parent_to_children, &$nontree)
{
$ret = $nontree [ $id ];
if (array_key_exists ($id, $parent_to_children)) {
$list_of_children = $parent_to_children [ $id ];
unset ($parent_to_children[$id]);
while (count ($list_of_children)) {
$child = array_shift ($list_of_children);
$ret['children'][$child] = make_tree_structure_recurse ($child, $parent_to_children, $nontree);
}
}
return $ret;
}
To see what this does, first try running it on a structure like this:
var $data = array (
0 => array('Name' => 'Kenny'),
1 => array('Name' => 'Lilo', 'Parent' => 0),
2 => array('Name' => 'Adrian', 'Parent' => 1)
3 => array('Name' => 'Mark', 'Parent' => 1)
);
var $tree = make_tree_structure($data, 'Parent');
If I’m not mistaken, you should get something like this out: (the “Parent” key would still be there, but I’m leaving it out for clarity)
array (
0 => array('Name' => 'Kenny', 'children' => array (
1 => array('Name' => 'Lilo', 'children' => array (
2 => array('Name' => 'Adrian')
3 => array('Name' => 'Mark')
)
)
)
Examine the code to see how it does this. Once you understand how this works, you can tweak it to work with your particular data.
Assuming you dont want any data/children tags in your array:
foreach ($this->db as $num => $category)
{
// save the data to the array
$this->tmp[$category->id] = array();
// save a reference to this item in the parent array
$this->tmp[$category->parent][$category->id] = &$this->tmp[$category->id];
$this->select_categories($category->id);
}
// the tree is at index $cat_id
return $this->tmp[$cat_id];
If you just need to retrieve the full tree out of the database, you can even simplify your query (get all records at once) and remove the recursive call in this function. You will need an extra check that will only set the $this->tmp[$catagory->id] when it does not exist and else it should merge the data with the existing data.

summarise php array into treeview

Array
(
[00000000017] => Array
(
[00000000018] => Array
(
[00000000035] => I-0SAYHADW4JJA
[00000000038] => I-RF10EHE25KY0
[00000000039] => I-8MG3B1GT406F
)
[00000000019] => I-7GM4G5N3SDJL
)
[00000000025] => Array
(
[00000000011] => I-HT34P06WNMGJ
[00000000029] => I-U5KKT1H8J39W
)
[00000000040] => I-GX43V2WP9KPD
[00000000048] => I-XM526USFJAH9
[00000000052] => I-M414RK3H987U
[00000000055] => I-GABD4G13WHX7
)
I have the above array and i want to create a treeview display..
any recommendation ?
I guess i have to elaborate furthe on my question..
I want to store those array according to the level of array..
Example , I want something look like this :
[level_1]=> 00000000017,00000000025,00000000040, 00000000048, 00000000052
[level_2]=> 00000000018,00000000019, 00000000011, 00000000029
[level_3]=> 00000000035, 00000000038, 00000000039
You want a modified breadth-first search. This has the correct results for your sample structure:
<?php
function BFTraverse(&$tree = NULL, $depth = 0)
{
if (empty($tree))
return FALSE;
$keys = array_keys($tree);
$struct["lvl_$depth"] = $keys;
foreach ($keys as $key)
{
if (is_array($tree[$key]))
{
$struct = array_merge_recursive($struct, BFTraverse($tree[$key], $depth + 1));
}
}
return $struct;
}
$data = array
('00000000017' => array
(
'00000000018' => array
(
'00000000035' => 'I-0SAYHADW4JJA',
'00000000038' => 'I-RF10EHE25KY0',
'00000000039' => 'I-8MG3B1GT406F'
),
'00000000019' => 'I-7GM4G5N3SDJL'
),
'00000000025' => array
(
'00000000011' => 'I-HT34P06WNMGJ',
'00000000029' => 'I-U5KKT1H8J39W'
),
'00000000040' => 'I-GX43V2WP9KPD',
'00000000048' => 'I-XM526USFJAH9',
'00000000052' => 'I-M414RK3H987U',
'00000000055' => 'I-GABD4G13WHX7'
);
$var = BFTraverse($data);
$i = 0;
foreach ($var as $level)
echo "Level " . ++$i . ': ' . implode(', ', $level) . "\n";
?>
The output is:
Level 1: 00000000017, 00000000025, 00000000040, 00000000048, 00000000052, 00000000055
Level 2: 00000000018, 00000000019, 00000000011, 00000000029
Level 3: 00000000035, 00000000038, 00000000039
edit: Modified in the sense that you want the keys and not the node values.
I ran into the same problem recently and this article by Kevin van Zonneveld helped me out.
Basically you have to use a recursive function. Check out the article, it's what you need!

Categories