How to dynamicly get a multi dimensional array? - php

My code just populates the last array in the array $workshops
my loop function populates array $workshops, like so
while (ECSE_purchase::have_products()) {
ECSE_purchase::the_product();
$prodid = ECSE_purchase_product::get_the_ID();
$workshop_data = ETICKETDATA::get_workshop_details_helper($prodid);
$workshops = array();
if($prodid == 565) {
............
} else {
$workshopsTmp = array();
$workshopsTmp['workshop_barcode'] = $data['workshop_barcode'];
$workshopsTmp['workshop_id'] = ECSE_purchase_product::get_the_ID();
$workshopsTmp['workshop_title'] = ECSE_purchase_product::get_the_name();
$workshopsTmp['workshop_time'] = $workshop_data['time'];
$workshopsTmp['workshop_room'] = $workshop_data['room'];
$workshopsTmp['workshop_num_of_tickets'] = ECSE_purchase_product::get_the_QTY();
$workshops[] = $workshopsTmp;
}
But here i just get the last array and not like this:
$workshops = array(array('workshop_barcode' => '0101010101',
'workshop_id' => '589',
'workshop_title' => 'Swimming',
'workshop_time' => '12:00',
'workshop_room' => 'Room 1',
'workshop_num_of_tickets' => '2'),
array('workshop_barcode' => '03030303003',
'workshop_id' => '568',
'workshop_title' => 'Running',
'workshop_time' => '15:00',
'workshop_room' => 'Room 3',
'workshop_num_of_tickets' => '3'),
array('workshop_barcode' => '0505050505',
'workshop_id' => '570',
'workshop_title' => 'Biking',
'workshop_time' => '16:00',
'workshop_room' => 'Room 2',
'workshop_num_of_tickets' => '2'));
Any pointers appreciated.
regards,
just edit the loop

You keep redefining your initial array. Try putting $workshops array before while loop
$workshops = array();
while (ECSE_purchase::have_products()) {
ECSE_purchase::the_product();
$prodid = ECSE_purchase_product::get_the_ID();
$workshop_data = ETICKETDATA::get_workshop_details_helper($prodid);
if($prodid == 565) {
............
} else {
$workshopsTmp = array();
$workshopsTmp['workshop_barcode'] = $data['workshop_barcode'];
$workshopsTmp['workshop_id'] = ECSE_purchase_product::get_the_ID();
$workshopsTmp['workshop_title'] = ECSE_purchase_product::get_the_name();
$workshopsTmp['workshop_time'] = $workshop_data['time'];
$workshopsTmp['workshop_room'] = $workshop_data['room'];
$workshopsTmp['workshop_num_of_tickets'] = ECSE_purchase_product::get_the_QTY();
$workshops[] = $workshopsTmp;
}

Related

How to compare and filter 2 arrays

first array like this
$zones_array1 = array();
$zones_array1[] = array('id' => 'Alabama', 'text' => 'Alabama');
$zones_array1[] = array('id' => 'Alaska', 'text' => 'Alaska');
$zones_array1[] = array('id' => 'Arizona', 'text' => 'Arizona');
$zones_array1[] = array('id' => 'Arkansas', 'text' => 'Arkansas');
second array like this
$zones_array2 = array();
$zones_array2[] = array('id' => 'Alaska', 'text' => 'Alaska');
$zones_array2[] = array('id' => 'Arizona', 'text' => 'Arizona');
i want filter these two array and i want final result as array like this
first array like this
$zones_array3 = array();
$zones_array3[] = array('id' => 'Alabama', 'text' => 'Alabama');
$zones_array3[] = array('id' => 'Arkansas', 'text' => 'Arkansas');
please help me
You can use php 'in_array' to check weather an element exists inside other array or not. In you case the array is multidimensional so stored all the id's inside a newly created array and then compared the given array with that.
$check_array = array();
foreach ($zones_array1 as $arr1){
$check_array[] = $arr1['id'];
}
$zones_array3 = array();
foreach ($zones_array2 as $arr2){
if (!in_array($arr2['id'], $check_array))
{
$zones_array3[] = $arr2;
}
}
echo '<pre>';
print_r($zones_array3);
Simply try:
function udiffCompare($a, $b)
{
return $a['id'] == $b['id'] ? 0 : -1;
}
$arrdiff = array_udiff($zones_array1, $zones_array2, 'udiffCompare');
echo '<pre>';
print_r($arrdiff);
array_udiff() compares each element of the first array-argument against all the elements of the second array-argument using the provided callback function. If the callback returns zero for any of the comparisons then the element of the array in the first argument will not be present in the returned array of the function.
You will try it :
function unique_multidim_array($array, $key){
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val){
if(!in_array($val[$key],$key_array)){
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$zones_array1 = array_merge($zones_array2, $zones_array3);
$zones_array1 = unique_multidim_array($zones_array1, 'id');
print_r($zones_array1);
Please try this
array_push($zones_array1,$zones_array2);
print_r(array_unique($zones_array1));
I am not sure.

PHP- Checking for sub-arrays in a multidimensional array

I have an array which contains the data to build a nav menu on the site.
This is how it's setup:
$menu = array();
$menu['0']['label'] = 'Home';
$menu['0']['icon'] = 'fa-home';
$menu['0']['id'] = '';
$menu['0']['class'] = '';
$menu['0']['url'] = '/index.php';
$menu['0']['blank'] = 0;
$menu['1']['label'] = 'Admin';
$menu['1']['icon'] = 'fa-user';
$menu['1']['id'] = '';
$menu['1']['class'] = '';
$menu['1']['url'] = '#';
$menu['1']['blank'] = 0;
$menu['1']['0']['label'] = 'Notes';
$menu['1']['0']['icon'] = '';
$menu['1']['0']['id'] = '';
$menu['1']['0']['class'] = '';
$menu['1']['0']['url'] = '/notes.php';
$menu['1']['0']['blank'] = 0;
$menu['1']['1']['label'] = 'Testing';
$menu['1']['1']['icon'] = '';
$menu['1']['1']['id'] = '';
$menu['1']['1']['class'] = '';
$menu['1']['1']['url'] = '/testing.php';
$menu['1']['1']['blank'] = 0;
$menu['2']['label'] = 'Resources';
$menu['2']['icon'] = 'fa-thumb-tack';
$menu['2']['id'] = '';
$menu['2']['class'] = '';
$menu['2']['url'] = '#';
$menu['2']['blank'] = 0;
Where $menu['0'], $menu['1'], etc. are all shown on the main nav menu. Any array underneath them, such as $menu['1']['0'] are all submenus under their parent.
I am trying to check each main element on the array to see if there is a sub-array (if there are any submenus to create).
foreach ($menu as $item) {
if (is_array($item)) {
foreach ($item as $subitem) {
print_r($subitem); // See notes below
}
}
}
What I am trying to do with print_r($subitem) is come up with an array like:
$subitem['label'] = 'Notes';
$subitem['icon'] = '';
$subitem['id'] = '';
$subitem['class'] = '';
$subitem['url'] = '/notes.php';
$subitem['blank'] = 0;
Ideas?
You should reorganize your array:
$menu[0] = ['items' => [], 'submenus' => []];
So all menus have an items key and a submenus key. In the submenus array, you should put an array that looks identical (that is, has and 'items' key and 'submenus' key).
That way you can just count() the submenus key and know if there are any submenus to create. It also will let you nest them as far as you want if you write a recursive function for the menu.
For example:
<?php
// feed this an initialized menu, and an array of items
function addMenuItem($menu, $options) {
$newItem = makeMenu();
$newItem['items'] = $options;
$menu[] = $newItem;
return $menu;
}
// the parent menu is first, submenu second
function addSubMenu($menu, $pos, $subMenu) {
$menu[$pos]['submenus'][] = $subMenu;
return $menu;
}
// create a 'valid' but empty menu array
function makeMenu() {
return array('items' => array(), 'submenus' => array());
}
?>
As a side note, this is something that would work really well in Classes instead of functions and arrays.
I think your current structure may already be very usable. Here is a modified version of your loop using the same data:
foreach ($menu as $parent_item) {
echo '<h2>Parent Items</h2>';
foreach ($parent_item as $key => $item) {
if (is_array($item)) {
echo '<br><h2>Subitems</h2>';
foreach ($item as $subkey => $subitem) {
echo "$subkey = $subitem<br>";
}
} else {
echo "$key = $item<br>";
}
}
echo '<br>';
}
And here is the output:
Parent Itemslabel = Homeicon = fa-homeid = class = url = /index.phpblank = 0Parent Itemslabel = Adminicon = fa-userid = class = url = #blank = 0Subitemslabel = Notesicon = id = class = url = /notes.phpblank = 0Subitemslabel = Testingicon = id = class = url = /testing.phpblank = 0Parent Itemslabel = Resourcesicon = fa-thumb-tackid = class = url = #blank = 0
try this code. It is alot easier to manage.
$menu = array('menu1'=>array(
'label'=>'Home',
'icon'=>'fa-home',
'id'=>'',
'class'=>'',
'url'=>'/index.php',
'blank'=>0),
'menu2'=>array(
'label'=>'Home',
'icon'=>'fa-home',
'id'=>'',
'class'=>'',
'url'=>'/index.php',
'blank'=>0),
'menu3'=>array(
'label'=>'Home',
'icon'=>'fa-home',
'id'=>'',
'class'=>'',
'url'=>'/index.php',
'blank'=>0),
);
//print_r($menu);
Array
(
[menu1] => Array
(
[label] => Home
[icon] => fa-home
[id] =>
[class] =>
[url] => /index.php
[blank] => 0
)
[menu2] => Array
(
[label] => Home
[icon] => fa-home
[id] =>
[class] =>
[url] => /index.php
[blank] => 0
)
[menu3] => Array
(
[label] => Home
[icon] => fa-home
[id] =>
[class] =>
[url] => /index.php
[blank] => 0
)
Consider this structure for your navigation links:
$links = [
'primary_navigation' => [
'children' => [
[
'label' => 'link'
],
[
'label' => 'link',
'children' => [
['label' => 'sublink'],
['label' => 'sublink'],
],
],
],
],
'secondary_navigation' => [
'children' => [
[
'label' => 'link'
],
[
'label' => 'link',
'children' => [
[
'label' => 'sublink'
],
[
'label' => 'sublink',
'children' => [/** ... **/],
],
],
],
],
],
];
This way you always know about your children and its obvious how to find them recursively.

PHP: create array from arrays

I have a form that is posting 4 arrays that I need to combine and eventually compose to email. The four arrays:
$quantityArray = $this->input->post('qty');
$dimensionArray = $this->input->post('dimension');
$thicknessArray = $this->input->post('thickness');
$descriptionArray = $this->input->post('description');
will all have the same array length and each index will be related. How do I combine the 4 arrays such as
[0]
'qty' => '1',
'dimenesion => '2x2',
'thickness' => '2in',
'description' => 'this is the description'
[1]
'qty' => '1',
'dimenesion => '2x2',
'thickness' => '2in',
'description' => 'this is the description'
I have tried array_combined, array_merged and can't get the results that I am looking for. Thanks for the help on this.
If you have same length for those arrays here is example code:
$resultArray = array();
foreach($quantityArray as $index => $qty) {
$resultArray[$index]['qty'] = $qty;
$resultArray[$index]['dimenesion'] = $dimensionArray[$index];
$resultArray[$index]['thickness'] = $thicknessArray[$index];
$resultArray[$index]['description'] = $descriptionArray [$index];
}
print_r($resultArray);
This also may work:
<?php
//...
$quantityArray = $this->input->post('qty');
$dimensionArray = $this->input->post('dimension');
$thicknessArray = $this->input->post('thickness');
$descriptionArray = $this->input->post('description');
//
// combine them:
//
$combined = array();
$n = count($quantityArray);
for($i = 0; $i < $n; $i++)
{
$combined[] = array(
'qty' => $quantityArray[$i],
'dimenesion' => $dimensionArray[$i],
'thickness' => $thicknessArray[$i],
'description' => $descriptionArray[$i]
);
}
//
echo "<pre>";
print_r($combined);
echo "</pre>";
?>
If we assume that we have same length for those arrays here is my codes:
$quantityArray = array(1, 1, 5, 3);
$dimensionArray = array("2x2", "3x3", "4x4", "2x2");
$thicknessArray = array("2in", "3in", "4in", "2in");
$descriptionArray = array("this is the description 1", "this is the description 2 ", "this is the description3 ", "this is the description4" );
$myCombinArray = array();
foreach ( $quantityArray as $idx => $val ) {
$subArray = array (
'qty' => $quantityArray [$idx],
'dimenesion' => $dimensionArray [$idx],
'thickness' => $thicknessArray [$idx],
'description' => $descriptionArray [$idx]
);
array_push ( $myCombinArray, $subArray );
}
print_r($myCombinArray);
How about an easy way if there are always those 4 arrays:
$quantityArray = $this->input->post('qty');
$dimensionArray = $this->input->post('dimension');
$thicknessArray = $this->input->post('thickness');
$descriptionArray = $this->input->post('description');
$combinedArray = [$quantityArray, $dimensionArray, $thicknessArray, $descriptionArray];
# old syntax:
# $combinedArray = array($quantityArray, $dimensionArray, $thicknessArray, $descriptionArray);

PHP grouping array

i've got the following array:
$comments = array();
$comments[] = array('member_id' => '17',
'time' => '2011-05-10 11:10:00',
'name' => 'John Smith',
'comment' => 'Test Comment 1');
$comments[] = array('member_id' => '25',
'time' => '2011-05-10 11:26:00',
'name' => 'David Jones',
'comment' => 'Test Comment 2');
$comments[] = array('member_id' => '17',
'time' => '2011-05-10 13:15:00',
'name' => 'John Smith',
'comment' => 'Test Comment 3');
How would i go about grouping it by member_id? So I'll be able to display the comments on the page with the following formatting:
John Smith(2 comments)
2011-05-10 11:10:00 | Test Comment 1
2011-05-10 13:15:00 | Test Comment 3
David Jones(1 comment)
2011-05-10 11:26:00 | Test Comment 2
One solution is to sort them by the name field (check out usort for that), but even easier might be to just populate a new array in this way:
$grouped = array();
foreach($comments as $c) {
if(!isset($grouped[$c['name']]) {
$grouped[$c['name']] = array();
}
$grouped[$c['name']][] = $c;
}
//Now it's just a matter of a double foreach to print them out:
foreach($grouped as $name => $group) {
//print header here
echo $name, "<br>\n";
foreach($group as $c) {
//print each comment here
}
}
I would suggest using a second grouping array
$groups[] = array();
foreach( $comment as $k=>$v ) {
$groups[$v['member_id']][] = $k
}
And then to print it
foreach( $group as $m_id=>$arr ) {
echo "Group $m_id<br/>\n";
foreach( $arr as $k ) {
echo $comment[$k]."<br/>\n";
}
}
You should try with taking multi-dimensional array.
$comment_groups[] = array();
$m_id = '';
foreach( $comment_groups as $key=>$val ) {
if($key == 'member_id'){
$m_id = $val;
}
$comment_groups[$m_id]][] = $val;
}
Then you can print as you want to display.

PHP multiple array - echoing the value of an array key using object

<?php
/* SC: Shop Category */
$SCStatement = "SELECT * FROM shop_categories";
$SCQuery = mysql_query($SCStatement);
while($SCFetch = mysql_fetch_array($SCQuery)){
$SCItems[] = array(
'id' => $SCFetch['id'],
'name' => $SCFetch['cat_name'],
'desc' => $SCFetch['cat_description']
);
}
$SCNumCols = 2;
$SCNumItems = count($SCItems);
$SCNumRows = ceil($SCNumItems / $SCNumCols);
function bindArrayToObject($array) {
$return = new stdClass();
foreach ($array as $k => $v) {
if (is_array($v)) {
$return->$k = bindArrayToObject($v);
}
else {
$return->$k = preg_replace ('/<[^>]*>/', '', $v);
}
}
return $return;
}
$newObject = bindArrayToObject($SCItems);
echo $newObject->name;
?>
The data i retrieve from the database is stored in $SCItems[] array. The problem is, when i echo the $newObject->name; nothing will appear. What to add this code to show the data using $newObject->name;
Thanks in advance.
Well, judging from this code, what you have is something like
$SCItems = Array(
0 => Array(
'id' => 1,
'name' => 'name 1',
'desc' => 'description 1'
),
1 => Array(
'id' => 2,
'name' => 'name 2',
'desc' => 'description 2'
),
);
And then from that your bindArrayToObject function trying to build the object
$newObject = new stdClass();
$newbject->0 = new stdClass();
$newbject->0->id = 1;
$newbject->0->name = 'name 1';
$newbject->0->desc = 'description 1';
$newbject->1 = new stdClass();
$newbject->1->id = 2;
$newbject->1->name = 'name 2';
$newbject->1->desc = 'description 2';
So, what you probably should do is loop over your '$SCItems' and then on each entry use bindArrayToObject
Such as
$SCObject = Array();
foreach($SCItems as $SCItem) {
$SCObjects[] = bindArrayToObject($SCItem);
}
From there you should be able to access $SCObjects[0]->name, which would make much more sense to me

Categories