Creating a multidimensional array and accessing fields - php

I have been running around in circles over this for days ... please help.
I am trying to create a multidimensional array based on the number of files in a directory and the parsed filename ...
foreach ($files as $file) {
echo "$file[0] $file[1] <br>\n" ; #file[0]=Unix timestamp; file[1]=filename
$pn = explode('.', $file[1]);
$ndt = explode('_',array_shift($pn)) ;
foreach ($ndt as $arndt) {
$items[$arndt] = $ndt ; //this part does not work
echo "$ndt[0] $ndt[1] $ndt[2] $ndt[3] $ndt[4]" ;
}
print_r($items[$arndt]) ;
}
The output of my array is this:
Array ( [0] => OLPH [1] => Barbecue [2] => 03132013 [3] => 11am [4] => 2pm )
Note: I just have 1 file in the directory for testing purposes, but there will be more, hence the need for a multidimensional array ...
I then try to access the array in my html using this:
<h4><?php echo "$items[$arndt]. $ndt[1]" ?></h4>
.... naturally, this output does not print the results that I want .... For every file[1] I want to be able to print $arndt[] and access it using $items[][] notation.... however it just prints Array[]Array[] .... Please help ?
Thanks in advance,
Carlos

echoing/printing an array in string context just gives you Array. If you're dealing with multi-dimensional arrays, each dimension has to have its own loop to print out its contents.
e.g.
$arr1d = array('foo' => 'bar'); // 1D array
echo $arr1d; // outputs "Array"
$arr2d = array('foo' => array('bar' => 'baz')); // 2D array
echo $arr2d; // outputs 'Array';
echo $arr2d['foo']; // outputs 'Array'
echo $arr2d['foo']['bar']; // outputs 'baz'
foreach($arr2d as $key1 => $val1) {
echo $val1; // outputs 'Array';
foreach($val1 as $key2 => $val2) {
echo $val; // outputs 'Baz'
}
}

Related

how to get the key and value in the object in list of array

How to get the distinct keys ($key) and multiple different values ($myObjectValues) in list of objects?
My expected outcome is distinct keys displays as column in table and its different values display as multiple rows. The column ($key) should not be hardcore and I plan to display in blade view.
Ideal:
Current Code:
foreach($x as $key => $item) {
print_r($key); //this is list number
foreach($item as $key => $myObjectValues){
print_r($key); //this is my object key
print_r($myObjectValues); //this is my object values
}
}
This is the json array object ($x).
Array(
[0] => stdClass Object
(
[milk_temperature] => 10
[coffeebean_level] => 124.022
)
[1] => stdClass Object
(
[milk_temperature] => 1099
[soya_temperature] => 10
[coffeebean_level] => 99.022
)
[2] => stdClass Object
(
[milk_temperature] => 1099
[coffeebean_level] => 99.022
)
)
You can do it like this, it's not the best approach in the world but it works and you can use it as an example. First you create a list with the table header titles and then start by printing the header and then the values.
<?php
$x = [
(object) [
'milk_temperature' => 10,
'coffeebean_level' => 124.022
],
(object) [
'milk_temperature' => 1099,
'soya_temperature' => 10,
'coffeebean_level' => 99.022
],
(object) [
'milk_temperature' => 1099,
'coffeebean_level' => 99.022
]
];
// list all the keys
$keys = [];
foreach($x as $key => $item) {
$keys = array_merge($keys, array_keys((array) $item));
}
$keys = array_unique($keys);
// echo the header
foreach ($keys as $key) {
echo $key . ' ';
}
echo "\n";
// echo the values
foreach($x as $item) {
foreach ($keys as $key) {
echo $item->$key ?? '-'; // PHP 7+ solution
// echo isset($item->$key) ? $item->$key : '-'; // PHP 5.6+
echo ' ';
}
echo "\n";
}
You can first get the keys of the array with array_keys() and array_collapse():
$columns = array_keys(array_collapse($records));
Then you look through the $records using the same loop you already have. Let's demo it with this example:
$columns = array_keys(array_collapse($records));
foreach($records as $key => $item) {
//these are each record
foreach ($columns as $column) {
//each column where you build the header
// converts $item to an array
$item = (array)$item;
if (! array_key_exists($column, (array)$item)) {
// show '---'
echo '---';
continue;
}
//show $item[$item]
echo $item[$column];
}
}
The great advantage of doing so i.e getting the columns first (apart from converting the stdClass to an array) is that the columns array can be used any way you deem fit.
It would be more beneficial if you can have your data all as array then you can easily use the array functions available on it.

PHP multidimensional array not giving output

I've tried to display this information tons of times, i've looked all over stackoverflow and just can't find an answer, this isn't a duplicate question, none of the solutions on here work. I've a json array which is stored as a string in a database, when it's taken from the database it's put into an array using json_decode and looks like this
Array
(
[0] => Array
(
[0] => Array
(
)
[1] => Array
(
[CanViewAdminCP] => Array
(
[Type] => System
[Description] => Grants user access to view specific page
[Colour] => blue
)
)
)
)
However, when i try to loop through this, it just returns nothing, I've tried looping using keys, i've tried foreach loops, nothing is returning the values, I'm looking to get the Array key so "CanViewAdminCP" and then the values inside that key such as "Type" and "Description".
Please can anybody help? thankyou.
Use a recursive function to search for the target key CanViewAdminCP recursively, as follows:
function find_value_by_key($haystack, $target_key)
{
$return = false;
foreach ($haystack as $key => $value)
{
if ($key === $target_key) {
return $value;
}
if (is_array($value)) {
$return = find_value_by_key($value, $target_key);
}
}
return $return;
}
Example:
print_r(find_value_by_key($data, 'CanViewAdminCP'));
Array
(
[Type] => System
[Description] => Grants user access to view specific page
[Colour] => blue
)
Visit this link to test it.
You have a 4 level multidimensional array (an array containing an array containing an array containing an array), so you will need four nested loops if you want to iterate over all keys/values.
This will output "System" directly:
<?php echo $myArray[0][1]['CanViewAdminCP']['Type']; ?>
[0] fetches the first entry of the top level array
[1] fetches the second entry of that array
['CanViewAdminCP'] fetches that keyed value of the third level array
['Type'] then fetches that keyed value of the fourth level array
Try this nested loop to understand how nested arrays work:
foreach($myArray as $k1=>$v1){
echo "Key level 1: ".$k1."\n";
foreach($v1 as $k2=>$v2){
echo "Key level 2: ".$k2."\n";
foreach($v2 as $k3=>$v3){
echo "Key level 3: ".$k3."\n";
}
}
}
Please consider following code which will not continue after finding the first occurrence of the key, unlike in Tommassos answer.
<?php
$yourArray =
array(
array(
array(),
array(
'CanViewAdminCP' => array(
'Type' => 'System',
'Description' => 'Grants user access to view specific page',
'Colour' => 'blue'
)
),
array(),
array(),
array()
)
);
$total_cycles = 0;
$count = 0;
$found = 0;
function searchKeyInMultiArray($array, $key) {
global $count, $found, $total_cycles;
$total_cycles++;
$count++;
if( isset($array[$key]) ) {
$found = $count;
return $array[$key];
} else {
foreach($array as $elem) {
if(is_array($elem))
$return = searchKeyInMultiArray($elem, $key);
if(!is_null($return)) break;
}
}
$count--;
return $return;
}
$myDesiredArray = searchKeyInMultiArray($yourArray, 'CanViewAdminCP');
print_r($myDesiredArray);
echo "<br>found in depth ".$found." and traversed ".$total_cycles." arrays";
?>

PHP Remove Multidimensional Array Value

I have array multidimensional code like this:
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
unset($array[$eaten]);
and what i need is to delete 'grape' from the array because 'grape' already eaten. how to fix my code to unset the 'grape'?
and my question number two, if it can be unset, is there a way to unset multi value like
unset($array,['grape','orange']);
thanks for help..
You can remove eaten element by following way. Use array_search() you can find key at the position of your eaten element.
Here below code shows that in any multidimensional array you can call given function.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
$array = removeElement($array, $eaten);
function removeElement($data_arr, $eaten)
{
foreach($data_arr as $k => $single)
{
if (count($single) != count($single, COUNT_RECURSIVE))
{
$data_arr[$k] = removeElement($single, $eaten);
}
else
{
if(($key = array_search($eaten, $single)) !== false)
{
unset($data_arr[$k][$key]);
}
}
}
return $data_arr;
}
P.S. Please note that you can unset() multiple elements in single call. But the way you are using unset is wrong.
Instead of using unset() i suggest you to create a new Array after removal of required value benefit is that, your original array will remain same, you can use it further:
Example:
// your array
$yourArr = array(
'fruits'=>array('apple','orange','grape', 'pineaple'),
'vegetables'=>array('tomato', 'potato')
);
// remove array that you need
$removeArr = array('grape','tomato');
$newArr = array();
foreach ($yourArr as $key => $value) {
foreach ($value as $finalVal) {
if(!in_array($finalVal, $removeArr)){ // check if available in removal array
$newArr[$key][] = $finalVal;
}
}
}
echo "<pre>";
print_r($newArr);
Result:
Array
(
[fruits] => Array
(
[0] => apple
[1] => orange
[2] => pineaple
)
[vegetables] => Array
(
[0] => potato
)
)
Explanation:
Using this array array('grape','tomato'); which will remove the value that you define in this array.
This is how I would do it.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$unset_item = 'grape';
$array = array_map(function($items) use ($unset_item) {
$found = array_search($unset_item, $items);
if($found){
unset($items[$found]);
}
return $items;
}, $array);

push array key and value in associative array

I want to push array into existing session array. I would like to use get[id] and I want to be able stack all the arrays added rather than delete them when a new array is pushed.
Bellow is my code and I am not getting the value, instead I get this error --- Array to string conversion. Thanks in advance.
**CODE
<?php
session_start();
if(empty($_SESSION['animals']))
{
$_SESSION['animals']=array();
}
// push array
array_push($_SESSION['animals'], array ( 'id' => "".$_GET['id'].""));
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo $key;
echo $value;
}
?>
With your code, this is what $_SESSION looks like:
array (size=1)
'animals' =>
array (size=1)
0 =>
array (size=1)
'id' => string 'test' (length=4)
In your code :
foreach($_SESSION['animals'] as $key=>$value)
key will contain 0 and value will contain array('id' => 'test'). Since value is an array, you cannot echo it like this.
If you want to echo all the characteristics of each animal, this code will work :
<?php
session_start();
if(empty($_SESSION['animals']))
{
$_SESSION['animals'] = array();
}
// push array
array_push($_SESSION['animals'], array ( 'id' => "".$_GET['id'].""));
// We go through each animal
foreach($_SESSION['animals'] as $key=>$animal)
{
echo 'Animal n°'.$key;
// Inside each animal, go through each attibute
foreach ($animal as $attribute => $value)
{
echo $attribute;
echo $value;
}
}

Different way to convert object to array using PHP

When use this code:
$array=(array)$yourObject;
The properties of $yourObject convert to index an array, but how can convert as one array, these means, the $yourObject be one index of $array and I echo $array[0] for access through object?!
Another way for question, please see this sample code:
<?php
$var1 = (string) 'a text';
$var2 = (array) array('foo', 'bar');
$var3 = (object) array("foo" => 1, "bar" => 2);
//It's OK.
foreach((array)$var1 as $v) {
echo $v."<br>";
}
echo "<hr>";
//It's OK.
foreach((array)$var2 as $v) {
echo $v."<br>";
}
echo "<hr>";
//It's NOT OK. I want through $var3 in output as an array with one index!
foreach((array)$var3 as $v) {
echo $v."<br>";
}
echo "<hr>";
?>
Other way:
I want use a variable in foreach but I not sure about type this, I want working foreach without error for any type variable (string, array, object,...)
For example I thinks must I have this sample output for some this types:
Output for $var1:
array
0 => string 'a text' (length=6)
Output for $var2:
array
0 => string 'foo' (length=3)
1 => string 'bar' (length=3)
Output for $var3:
array
0 =>
object(stdClass)[1]
public 'foo' => int 1
public 'bar' => int 2
And the end I sure the foreach return current result without error.
You mean to wrap your object inside an array?
$array = array($yourObject);
As mentioned by mc10, you can use the new short array syntax as of PHP 5.4:
$array = [$yourObject];

Categories