How to access elements inside MultiDimensional Array in php - php

How to access all the elements under each key of multidimensional array.
$multi = array
(
"Abhishek" => array("Choudhary", "Bunta", "Popy"),
"Bond" => array("One", "two", "three", "four"),
"Super" => array("T1", "T2")
);
$data = array("Abhishek","Bond","Super");
for($j = 0;$j<count($data);$j++)
{
echo "<br/>Main Array Value ".$data[$j]."<br/>";
for($i = 0;$i<count($data[$j]);$i++)
{
echo "sub Value ".$multi[$data[$j]][$i]." count ".count($data[$j]) ;
}
}
Now I want to iterate through each element of Abhishek , Bond and Super , so we can see Abhishek has 3 elements inside it but $data[$j] always return 1. If I increment then I can access Bunta
Currently the output is -
Main Array Value Abhishek
sub Value Bunta
Main Array Value Bond
sub Value two
Main Array Value Super
sub Value T2
and expected is:
**
Main Array Value Abhishek
sub Value choudhary
sub Value Bunta
sub Value Popy
:
:
Main Array Value Bond
sub Value two
Main Array Value Super
sub Value T2
**
Disclaimer : I am super new to PHP so may be my expectation can be invalid or I am missing some very silly thing.

i recommend you read some articles about multidim arrays, anyway your needs could be done with following code:
foreach($multi as $key => $value) {
echo "<br/>Main Array Value ".$key."<br/>";
for($i = 0; $i < sizeof($value); $i++) {
echo "sub Value ".$value[$i]." count ".sizeof($value) ;
}
}
PS: you don't need $data array

#bunta please check this out: PHP Foreach
You could use foreach instead.
Also:
PHP foreach loop through multidimensional array
HTH.

Using foreach() would be easier
foreach ($multi as $key => $subarray)
{
echo $key . '<br />';
foreach ($subarray as $subvalue)
{
echo ' - '.$subvalue . '<br />';
}
}
Will output
Abhishek
- Choudhary
- Bunta
- Popy
Bond
- One
- two
- three
- four
Super
- T1
- T2

Try this :
<?php
foreach($multi as $key => $value) {
echo "<br/>Parent Value ".$key."<br/>";
for($i = 0; $ < sizeof($value); $++) {
echo "Child Value ".$value[$i]." count ".sizeof($value) ;
}
}
?>
You are using wrong syntax to access it.
Thanks

All you need is use foreach to iterate on $multi array (if you just want to know the number of subelements for each element level 1):
<?php
echo "<br\>multiDimensional Array<br\>";
$multi = array("Abhishek" =>array
("Choudhary",
"Bunta",
"Popy"),
"Bond" => array
("One",
"two",
"three",
"four"),
"Super" => array
("T1",
"T2")
);
foreach( $multi as $value ){
echo " count ".count($value) ;
}

Related

PHP Aligning multiple arrays of different lengths

I'm probably just overlooking the obvious but I'd like to blame it on the fact that I'm new to PHP.
I have some number of arrays being returned with similar information but differing amounts of it.
I'll put some example arrays below:
(t1-s1-1=1, t1-s1-2=1, t1-s2-1=1, t1-s2-2=1)
(t2-s1-1=1, t2-s2-1=2, t2-s2-2=1)
(t3-s1-1=1, t3-s2-1=1, t3-s3-1=1, t3-s3-2=3)
So I would like to make a table out of this information. Something like this:
test .. s1-1 .. s1-2 .. s2-1 .. s2-2 .. s3-1 .. s3-2
t1 ........1 .....1 ..........1 ....... 1.........1..........1
t2 ........1 .......X..........1..........1........1..........1
t3 ........1 .......X..........1..........X........1..........1
( where x is something that wasn't there. )
So every array has an s1 but could have s1-1, s1-2, s1-3 or simply s1-1. That creates very different sized arrays.
The problem is that each array can have wildly different information and because they are Indexed arrays instead of Associative arrays I'm not sure how to best equalize them. I can't consistently say index 3 is s1-3 or something else.
I can't just loop through manually because I never know where a gap will appear. I can't look for specific indexes because the arrays aren't associative so the titles are built into the value and I don't know how to access them separately.
Any good ideas out there that maybe a newbie is overlooking? I'm open to non-tabular display ideas as well as long as I can easily sort and display the information.
Thanks
I'm assuming your original arrays contain values as string, so for instance, in PHP syntax, they look like:
['t1-s1-1=1', 't1-s1-2=1', 't1-s2-1=1', 't1-s2-2=1']
Basically, you should create a bi-dimensional array:
go through all arrays and by using a regex extract the different parts, that is, for the first element in the array above: t1 (the index for the first level in the bi-dimensional array), s1-1 (the index for the second level in the bi-dimensional array) and the value 1
insert the value in the bi-dimensional array
keep in a separate array, let's call it allColumns every second index above (sx-y), even you will have duplicate values you can, at the end, delete those duplicate and order it alphabetically
After that, you will have all the value in the bi-dimensional array but you still miss the gaps, so what you can do it iterate over the bi-dimensional array, and for every dimension tz (t1, t2,...), go through for all the values stored in allColumns and if you don't find the entry for that sx-y in the bi-dimensional array for that tz, add it with value x (or probably with value = 0)
I think an example can clarify the above:
// arrays of arrays, I don't know how you receive the data
$arrays = [
['t1-s1-1=1', 't1-s1-2=1', 't1-s2-1=1', 't1-s2-2=1'],
['t2-s1-1=1', 't2-s2-1=2', 't2-s2-2=1'],
['t3-s1-1=1', 't3-s2-1=1', 't3-s3-1=1', 't3-s3-2=3']
];
// bi-dimensional array
$output = [];
// it will store all columns you find in the $arrays entry
$allColumns = [];
// iterate for every array you receive, i.e. ['t1-s1-1=1', 't1-s1-2=1', 't1-s2-1=1', 't1-s2-2=1']
foreach ($arrays as $array) {
// iterate over every element in the array: 't1-s1-1=1', 't1-s1-2=1', 't1-s2-1=1' and 't1-s2-2=1'
foreach ($array as $item) {
// extract the parts on every element: $matches is an array containing the different parts
preg_match('/^(t\d+)-(s\d+-\d+)=(\d+)/', $item, $matches);
/**
* $matches[0] would contains the element if matched: 't1-s1-1=1'
* $matches[1] would contains 't1' if matched
* $matches[2] would contains 's1-1' if matched
* $matches[2] would contains 1 (integer) if matched
*/
if (!empty($matches)) {
$output[$matches[1]][$matches[2]] = $matches[3];
$allColumns[] = $matches[2];
}
}
}
// clean duplicates
$allColumns = array_unique($allColumns);
// sort values alphabetically
sort($allColumns);
// iterate over the just created bi-dimensional array
foreach ($output as $row => $columns) {
// iterate for all columns collected before
foreach ($allColumns as $column) {
// if one of column in 'allColumns' doesn't exit in $output you added in the correct place adding a zero value
if (!in_array($column, array_keys($columns))) {
$output[$row][$column] = 0;
}
}
}
To print the output you should only iterate over $ouput
This will be the array internally:
(
[t1] => Array
(
[s1-1] => 1
[s1-2] => 1
[s2-1] => 1
[s2-2] => 1
[s3-1] => 0
[s3-2] => 0
)
[t2] => Array
(
[s1-1] => 1
[s2-1] => 2
[s2-2] => 1
[s1-2] => 0
[s3-1] => 0
[s3-2] => 0
)
[t3] => Array
(
[s1-1] => 1
[s2-1] => 1
[s3-1] => 1
[s3-2] => 3
[s1-2] => 0
[s2-2] => 0
)
)
It exists other ways to implement the above, like skip the step where you fill the gaps and do it on the fly, ...
Updated
The simplest way to display the results in a HTML page is by embedding a php script to iterate over the associative array and compose the HTML table (I encourage you to study and research MVC to separate logic from the view)
<!DOCTYPE html>
<?php
// arrays of arrays, I don't know how you receive the data
$arrays = [
['t1-s1-1=1', 't1-s1-2=1', 't1-s2-1=1', 't1-s2-2=1'],
['t2-s1-1=1', 't2-s2-1=2', 't2-s2-2=1'],
['t3-s1-1=1', 't3-s2-1=1', 't3-s3-1=1', 't3-s3-2=3']
];
// bi-dimensional array
$output = [];
// it will store all columns you find in the $arrays entry
$allColumns = [];
// iterate for every array you receive, i.e. ['t1-s1-1=1', 't1-s1-2=1', 't1-s2-1=1', 't1-s2-2=1']
foreach ($arrays as $array) {
// iterate over every element in the array: 't1-s1-1=1', 't1-s1-2=1', 't1-s2-1=1' and 't1-s2-2=1'
foreach ($array as $item) {
// extract the parts on every element: $matches is an array containing the different parts
preg_match('/^(t\d+)-(s\d+-\d+)=(\d+)/', $item, $matches);
/**
* $matches[0] would contains the element if matched: 't1-s1-1=1'
* $matches[1] would contains 't1' if matched
* $matches[2] would contains 's1-1' if matched
* $matches[2] would contains 1 (integer) if matched
*/
if (!empty($matches)) {
$output[$matches[1]][$matches[2]] = $matches[3];
$allColumns[] = $matches[2];
}
}
}
// clean duplicates
$allColumns = array_unique($allColumns);
// sort values alphabetically
sort($allColumns);
// iterate over the just created bi-dimensional array
foreach ($output as $row => $columns) {
// iterate for all columns collected before
foreach ($allColumns as $column) {
// if one of column in 'allColumns' doesn't exit in $output you added in the correct place adding a zero value
if (!in_array($column, array_keys($columns))) {
$output[$row][$column] = 0;
}
}
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table Page</title>
</head>
<body>
<table>
<thead>
<?php
echo '<tr><th>Test</th>';
foreach ($allColumns as $head) {
echo sprintf('<th>%s</th>', $head);
}
echo '</tr>';
?>
</thead>
<tbody>
<?php
foreach ($output as $key => $columns) {
echo sprintf('<tr><td>%s</td>', $key);
foreach ($columns as $column) {
echo sprintf('<td>%s</td>', $column);
}
echo '</tr>';
}
?>
</tbody>
</table>
</body>
</html>
Try the following:
$final_array = array();
$temp_array = array();
foreach ($t1 as $t) {
$isin = 0;
$expression = substr($t, 0, strpos($t, "="));
$expression = str_replace("t1-", "" , $expression)
$value = substr($t, strpos($t, "=") + 1);
for ($i = 0; $i < 3; $i++) {
foreach ($x = 0; $x < 3; $x++) {
if ($expression == "s{$i}-{$x}") {
$isin = 1;
array_push($temp_array, $value);
}
}
}
if ($isin == 0) { array_push($temp_array, "X"); }
}
array_push($final_array, $temp_array);
It's not a great solution because you're choosing to do this in a really odd way but you should see the gist of what how to get what you want from this example.

PHP: Associate array index name in a foreach loop

I can get the index number from a foreach loop by doing the following.
foreach ($rows as $index=>$row)
{
echo $index.": ".$row;
// gives me "1: $row etc
}
If my array is associative is there away to get the associative name instead of the index number into my loop?
Actually you allready did it:
$associativeArray = array(
'First' => 1,
'Second' => 2,
'Third' => 3,
);
foreach ($associativeArray as $index => $value) {
echo $index . ": " . $value;
}
// First: 1
// Second: 2
// Third: 3
<?
$rows = array();
$rows['hi'] = 'there';
$rows['foo'] = 'bar';
foreach ($rows as $index=>$row)
{
echo $index.": ".$row;
// $index will be hi and foo
}
?>
PHP arrays ARE associative where regular arrays just have integers as keys.
The PHP documentation actually mentions this in the first sentence: http://php.net/manual/en/language.types.array.php
An array in PHP is actually an ordered map..
PHP doesn't have arrays, it has maps/dictionaries that are called arrays but they are not arrays like in other languages.

How to find the first, second, third etc numbers of an array

I've started learning about arrays and they've very confusing. I want to generate 4 numbers using this:
$numbers = range(1,4);
Then I shuffle with this:
shuffle($numbers);
Now I want to get each number as a variable, I've been told the best way is arrays. I have this code:
foreach($numbers as $number){
$test = array("first"=>"$number");
echo $test['first'];
}
What this does is echo all 4 numbers together, like "3142" or "3241" etc. Which is close to what I want, but I need all 4 numbers to have their own variable each. So I made this:
foreach($numbers as $number){
$test = array("first"=>"$number","second"=>"$number","third"=>"$number","fourth"=>"$number");
echo $test['first']," ",$test['second']," ",$test['third']," ",$test['fourth']," <br>";
}
This just echoes the 4 numbers 4 times. I need "first" to be the first number, "second" to be the second number of the 4 and the same for the third and fourth. I've been searching the web but don't know specifically what to search for to find the answer.
If someone answers could they please put as much detail into what certain functions do as possible, I want to learn not just get working code :)
You can use sizeof() it is return size of array size, and pass the key value manually. Like-
echo $numbers[0];
echo $numbers[1];
echo $numbers[2];
Here is a full code, try it
$numbers = range(1,4); //generate four numbers
shuffle($numbers); //shuffle them
$test = array(); //create array for the results
$words = array("1st", "2nd", "3rd", "4th","5th"); //create your array keys
$i=0;
foreach($numbers as $number){
$test[] = array($words[$i]=>$number); //add your array keys & values
$i++;
}
print_r($test); //show your results
If my understanding is correct you have an array and you want certain values from within it?
Then why not just use the array keys:
$array = array('peach','pear','apple','orange','banana');
echo $array[0]; // peach
echo $array[1]; // pear
echo $array[2]; // apple
Or you could loop through the array like so:
foreach ($array as $arrayKey => $arrayValue) {
// First value in the array is now below
echo $arrayKey; // 0
echo $arrayValue; // peach
}
You can also check if a value is in an array like so:
if (in_array('orange', $array)) {
echo 'yes';
}
Edit:
// Our array values
$array = array('peach','pear','apple','orange','banana');
// We won't shuffle for the example, we need expected results
#$array = shuffle($array);
// We want the first 3 values of the array
$keysRequired = array(0,1,2);
// This will hold our results
$storageArray = array();
// So for the first iteration of the loop $arrayKey is going to be 0
foreach ($array as $arrayKey => $arrayValue) {
// If the array key matches one of the values in the required array
if (in_array($arrayKey, $keysRequired)) {
// Store it within the storage array so we know what value it is
$storageArray[] = $arrayValue;
}
}
// Let's see what values have been stored
echo "<pre>";
print_r($storageArray);
echo "</pre>";
Would give you the following:
Array
(
[0] => 'peach'
[1] => 'pear'
[2] => 'apple'
)
Try this:
<?php
$numbers = range(1,4);
shuffle($numbers);
$test = array();
foreach($numbers as $k=>$v){
$test[$k] = $v;
}
echo "<pre>";
print_r($test);
?>
This will give you the output as:
Array
(
[0] => 3
[1] => 4
[2] => 2
[3] => 1
)
After that you can do:
$myvar["first"] = $test[0];
$myvar["second"] = $test[1];
$myvar["third"] = $test[2];
$myvar["fourth"] = $test[3];
Every array has a key, value pair, if you have an array say:
$myarr = array("a", "b", "c");
then you can access the value "a" as $myarr[0], "b" as $myarr[1] and so on.
In the for loop I am looping through the array with their key and value, this will not only give you the key of the array but also the value associated with that key.
More on Array
Edit:
Improving what Luthando Loot answered:
<?php
$numbers = range(1,4);//generate four numbers
shuffle($numbers);//shuffle them
$test = array();//create array for the results
$words = array("first", "second", "third", "fourth"); //create your array keys
$i = 0;
foreach($numbers as $number){
$test[$words[$i]] = $number;//add your array keys & values
$i++;
}
echo "<pre>";
print_r($test); //show your results
?>
Output:
Array
(
[first] => 4
[second] => 3
[third] => 2
[fourth] => 1
)
use this way
$numbers[0];
$numbers[1];
$numbers[2];
$numbers[3];
Firstly make an array of keys as
$key = ['first','second','third','fourth'];
And then you can simply use array_combine as
$numbers = range(1,4);
shuffle($numbers);
$key = ['first','second','third','fourth'];
$result = array_combine($key,$numbers);
Demo

PHP get ranges of same values from array

Is there any way to get the key range of same values and make a new array?
Let's say we have an Array Like this in php :
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b','6'=>'a','7'=>'a'];
How can i get this array? Is there any function for this?
$second_array = ['1-3'=>'a','4-5'=>'b','6-7'=>'a'];
Loop through it, extract the keys, generate the ranges and insert to the new array -
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b'];
$flip = array();
foreach($first_array as $key => $val) {
$flip[$val][] = $key;
}
$second_array = [];
foreach($flip as $key => $value) {
$newKey = array_shift($value).' - '.end($value);
$second_array[$newKey] = $key;
}
Output
array(2) {
["1 - 3"]=>
string(1) "a"
["4 - 5"]=>
string(1) "b"
}
regarding your first question you can get range of each value using foreach() loop.
$first_array = ['1'=>'a','2'=>'a','3'=>'a','4'=>'b','5'=>'b'];
foreach($first_array as $key=>$value)
{
//do your coding here, $key is the index of the array and $value is the value at that range, you can use that index and value to perform array manipulations
}
Regarding your second question it not exactly clear what are trying to implement there. But what ever you want to do like creating a new array with modified index and other things can be done within this foreach() loop itself
I hope this helps you.
If someone is still looking for an answer, here is what I did.
Given the array
$first_array = ['0'=>'a',
'1'=>'a',
'2'=>'a',
'3'=>'a',
'4'=>'a',
'5'=>'b',
'6'=>'b',
'7'=>'a',
'8'=>'a']
I build a multidimensional array, in which each element is an array of three more elements:
[0] - The value in the first array
[1] - The key where the value starts repeating
[2] - The last key where the value stops repeating
The code
$arrayRange = [];
for($i = 0; $i < count($first_array); $i++){
if(count($arrayRange) == 0){
// The multidimensional array is still empty
$arrayRange[0] = array($first_array[$i], $i, $i);
}else{
if($first_array[$i] == $arrayRange[count($arrayRange)-1][0]){
// It's still the same value, I update the value of the last key
$arrayRange[count($arrayRange)-1][2] = $i;
}else{
// It's a new value, I insert a new array
$arrayRange[count($arrayRange)] = array($first_array[$i], $i, $i);
}
}
}
This way you get a multidimensional array like this:
$arrayRange[0] = array['a', 0, 4];
$arrayRange[1] = array['b', 5, 6];
$arrayRange[2] = array['a', 7, 8];

Use PHP get_defined_vars to print names of all arrays with < n elements

I'm trying to use PHP's get_defined_vars function to print a list of variable names where the variable has less than n elements (we only want arrays here).
I can get it to print out the contents of each relevant array itself, but can't figure out how to make it just give the name of the variable.
Trying to use this:
//Get all of the variables as an array
$variables = get_defined_vars();
foreach ( $variables as $item ) {
if ( is_array($item) ) {
//Count the number of elements in this array
$elements = count($item);
//If there's less than 3 elements, print the array
if ( $elements < 3 ) {
echo "<p>";
print_r($item);
echo "</p><br />";
}
}
}
As I say, that gives the contents of any array variable with less than 3 elements. Any idea how to get it to just give the name of the variable? Is that even possible?
Use foreach($variables as $varName => $item) to also get the name of the variable:
foreach ( $variables as $varName => $item ) {
if ( is_array($item) ) {
//If there's less than 3 elements, print the array
if ( count($item) < 3 ) {
echo "<p>$varName</p>";
}
}
}
if you did this:
foreach(get_defined_vars() as $key=>$val)
{
//$key gives the name of the array
}

Categories