Associative array of arrays - php

Ive come upon the following code and having trouble deciphering its use.
(changed up the variable names a bit for simplicity)
$fooo = array(
'dog' => array('pages', 'home'),
'cat' => array('users', 'login'),
'bird' => array('users', 'reset', 1),
);
I am familiar with associative arrays but have not seen this "nested array" implementation before.
Is this code creating an array of arrays?
For example, $fooo['dog'] returns an array where $dog[0]='pages' and $dog[1]='home'
That seems wrong.

Yes, this is an array of arrays. But it perhaps may be more accurate to describe it as an associative array with an indexed array for every value.
The following can be done with it:
$fooo['dog'] // gets array("pages", "home")
$fooo['bird'][0] // gets "users"
$fooo['cat'][1] // gets "login"
$fooo['cow'] = array('x', 'y'); // adds another value to the outer array
$fooo['bird'][] = 2; // $fooo['bird'] now equals array('users', 'reset', 1, 2)
There is nothing wrong with this code, but your example is lacking practicality. There is plenty of code that uses such structures though. For example, a logical representation of a menu with sub-menus on a website (which seems like the source of your sample), this data structure can then be looped to generate an HTML/CSS menu.

Related

PHP fill up multidimensional associative array - easiest way

I want to use $_SESSION to store items in cart. The items are defined by id, each item has 3 sizes and for each size there will be stored item's quantity. I would like to use multidimensional associative array like that
$_SESSION['cart']['id'.$_GET['id']]['size'.$_POST['size']]['quantity'] += $_POST['quantity'];
but I guess the problem which I am getting (Notice: Undefined index) is because the arrays are not defined first.
I would like to keep it simple, so what would be the easiest way?
Your issue is that you're just assuming the items are set in $_SESSION. You need to assume they aren't and start by adding them in.
You'd harness isset().
if(!isset($_SESSION['cart']['id'.$_GET['id']])) {
$_SESSION['cart']['id'.$_GET['id']] = array(
'sizeONE' => array(
'quantity' => 0
),
'sizeTWO' => array(
'quantity' => 0
),
'sizeTHREE' => array(
'quantity' => 0
),
);
}
You'd obviously modify the above to probably only set the product id as you require then run through the same sort of isset() to add the selected sizes. I'm just showing you how to create the initial structure array.
I'd argue the best manner to store this data isn't in a multidimensional array, but rather in an Object (and not in $_SESSION, but that's a whole different topic).
If you want to approach this with an object, I'd use a variation of the following:
$myItem = new stdClass;
$myItem->id = $_GET['id'];
$myItem->sizeOne = new stdClass;
$myItem->sizeOne->name = "sizeOne";
$myItem->sizeOne->quantity = 1;
// repeat for sizeTwo and sizeThree
$_SESSION['cart'][$myItem->id] = $myItem;
Benefits:
More of an OOP approach to your program.
Drawbacks:
Storing an Object in the $_SESSION may cause scalability issues.

PHP Function with array_search Not working

I have a function using array_search not working ... here is my code
function LangFull($name){
$languageCodes = array(
"abkhazian"=>"ab",
"afar"=>"aa",
"afrikaans"=>"af",
"afrikaans"=>"af-za",
"zulu"=>"zu",
"zulu"=>"zu-za"
);
return ucwords(array_search(strtolower($name),$languageCodes));
}
echo LangFull("zu"); /// Gives no output
echo LangFull("zu-za"); /// Gives output
same with af is no output ... please help
If its possible to interchange, (values to keys and keys to values) and won't have those key collisions, then you can do it that way also:
function LangFull($name){
$languageCodes = array(
"ab" => "abkhazian",
"aa" => "afar",
"af" => "afrikaans",
"af-za" => "afrikaans",
"zu" => "zulu",
"zu-za" => "zulu",
);
return isset($languageCodes[$name]) ? ucwords(strtolower($languageCodes[$name])) : 'Not found';
}
echo LangFull("zu"); /// Gives output
echo LangFull("zu-za"); /// Gives output
echo LangFull("yahoo!");
You have two identical array keys:
"zulu"=>"zu",
"zulu"=>"zu-za"
You need to name one of them something else.
As they are the same, trying to access one of them specifically is futile as PHP does not know which of the two you are requesting.
Alternatively, if you are trying to store more than 1 data value for a given key, you can make the value of a key an array, so can then store more data as required.
e.g.
array (
"afrikaans"=> array(
"af",
"af-za",
),
"zulu"=> array(
"zu",
"zu-za",
)
);
EDIT.
In response to you asking about swapping the keys and values:
You can, and Ghost has shown you how.
However retaining your keys as they are (as my above array example) allows you to collate all relevant data into one index, and can access it easily.
Swapping values and keys will likely make it harder to obtain data you need, as your key is now the "data". So to grab data from an array you'd need to know the data (as it's now the key) and you'd actually be grabbing the reference (what was your key).
Which is a bit odd. It can work, but it's not really ideal.

Change position of elements in array

I have a simple question:
Query returns array in which I would like to change order of elements in PHP.
I have an array like this:
$typesSumAr = array( 'break', 'private absence', 'sick leave', 'vacation', 'work', 'work absence' );
I would like to have an array in this order:
$typesSumAr = array( 'work', 'break', 'sick leave', 'vacation', 'private absence', 'work absence' );
The are not always all elements in array, it could be only two for example, so I cannot hardcode the array. Do I need to make if statemenets to find out if key exists and then order it manually?
Thank you for your answer.
Seeing as you have an array in the order you prefer, your problem boils down to keeping the elements that are also present in another array. PHP has a function for exactly that: array_intersect
array_intersect returns an array containing all the values of its first array argument that are present in all the arguments. Note that keys are preserved.
There are lots of great array sorting function depending on how you want to sort it. Have a look here http://www.php.net/manual/en/array.sorting.php or even based on your own function via uksort (http://www.php.net/manual/en/function.uksort.php)

Can PHP Array Keys have an Alias?

This is just a curious question, the reasoning behind it is purely to be slightly more lazy on my part. Here is what I mean..
Say I have a website, where htaccess makes nice urls, and sends that data to the $_GET['p'] array key as the current 'page'. In the index file, I setup the page, and the first thing I do is setup some page settings in a config file, $_PAGE array. Now, say I have multiple pages I want to have the same settings, (and down in the page, other things may slightly change that do not correspond to the settings. So currently, I have something that looks like the following 2 php files.
// index.php
include('page.array.php');
echo '<title>'.$_PAGE[$_GET['p']]['title'].'</title>';
// page.array.php
$_PAGE = array(
'some/page/' => array(
'title' => 'This is an example'
)
)
$_PAGE['some/aliased/page/'] = $_PAGE['some/page/'];
Notice that at the end ofthe page array, in order to 'alias' a page I must add this to the end after the array has been created.
Is there any method in php that maybe I am just unaware of, that could make me a tad bit lazier (and at the same time add to cleaner code), and make it so I can simply alias the key? I notice the following doesn't work, and I suppose my question is, is there any way to create the alias within the same array during the creation of the array?
This example deosn't work:
// page.array.php
$_PAGE = array(
'some/page/' => array(
'title' => 'This is an example'
),
'some/aliased/page/' => $_PAGE['some/page/']
)
Maybe a way to refer to "this" array, from within itself?
If this is not possible, I don't have an issue with the "Not Possible" answer. Though if you have a better method of solving this, other then the way I have described above, in the sake of being lazier, I would be interested in reading it :)
I don't believe you can have array values that mirror other values in the array like this. The first thing that comes to mind though would be for you to construct your $_PAGE array from within a switch statement, using fall-through values as aliases:
// Define path for testing, and empty page array
$path = "some/aliased/page";
$page = Array();
// Time to evaluate our path
switch ($path) {
// If it's either of these two cases
case "some/page":
case "some/aliased/page":
// Assign this array to $page
$page = Array("Title" => "Two Paths, One Page.");
break;
// If it's this case
case "some/other/path":
// Assign this array to $page
$page = Array("Title" => "Something else.");
break;
// If the path isn't found, default data
default:
$page = Array("Title" => "Page not found");
}
// Output the result
var_dump($page);
Execute it: http://sandbox.onlinephpfunctions...ebd3dee1f37c5612c25
It's possible:
$_PAGE = array('some/page/' => array('title' => 'This is an example'));
$_PAGE['some/aliased/page/'] = &$_PAGE['some/page/'];
$_PAGE['some/page/'] = 7;
var_dump($_PAGE);
Use the & to get a reference to a (non-object) variable instead of its value.

How to merge multiple arrays that are depending on a function in PHP?

I am seeking for someone's knowledge out here.
Right now, I would need to merge several arrays into a bigger one, but all of those arrays depend on a function.
This function returns a numeric array containing different quantities of numbers between 1 and 7 :
function Possible($i, $j, $grid)
$possible = Possible($i, $j, $grid)
I'm working with a grid, and the function returns a different array for every case of the grid. What I would like to do is to merge those 7 arrays into another one. Some numbers may be present more than once in this big array, but I want it this way.
I tried using for loops, while loops and some other techniques, but nothing worked. In this case, it is not possible to manually define every array, since they change depending of what is contained in the grid and there are too many. It has to be done automatically, and this is where I get stuck.
for ($jj=0; $j<7; $j++){
$possRow = array_merge( ###what do I add here or what do I change in this code to make everything work###
Thank you if someone can help me out!
Etpi
hope this help:
$biggerOneArray = array();
for($k=0;$k<7;$k++) {
$biggerOneArray[] = Possible($i,$j,$grid);
}
Then you can check your bigger array, may contains all arrays of the iterations of the loop (7 arrays merged).
var_dump($biggerOneArray);
The output should be this:
array(
(int) 0 => array(
'key' => 'value',
'key2' => 'value2'
),
(int) 1 => array(
'key3' => 'value3',
'key4' => 'value4'
)
)
etc...
I'm sorry but your description isn't very clear. But just to get you started you might look at this solution.
function Possible($i, $j, $grid) {
// some code ... e.g. $array[] = "some data";
return $array;
}
By creating a small array for each grid and returning it using return $array you get a few little arrays which you can inturn place into a for loop to merge it into one larger array. However i believe the var $jj must have some meaning in the function it self as well.
for($jj=0;$jj<7;$jj++) {
$merged_array[$jj] = Possible($i,$j,$grid);
}
Maybe if you descripe your problem a little more and post an exmple of the array's your working with i can give you a better answer.

Categories