List values in multi-dimensional array in php - php

I have been working on this a while. I see multi-dimensional arrays in php are not that easy.
Here is my code:
while (list($key,$value) = each ($x))
{
Print "$key => $value\n<br>\n";
}
This works well to display the keys of the main array. what I get is :
visitors => Array
actions => Array
actions-average => Array
time-average => Array
pages-entrance => Array
What I want is the visitors and the value (number of visitors), value of actions, etc.
I want to then save the value in Mysql. Some I will have to convert from a string to and int or date.
I need to list one more level deep. But I cannot see how to do this.
--------------Added -----------
So what I have is an array of arrays. I need to step through each array.

did you try print_r ?
if you need more control over formatting then embedded loops as suggested by #Nick is the best option. Although it would be more natural and safer to use foreach loops rather than while.
foreach($x as $key => $value){
foreach( $value as $key2 => $value2){
print "$key $key2 => $value2\n<br />\n";
}
}
see PHP manual: each , there is a "caution" frame.
EDIT 1
I update sample code above for 2 day array.
It seems your array has more than 2 dimension. Then you should use recursion.
function my_print_r($x,$header="")
{
foreach($x as $key => $value){
if(is_array($value))
my_print_r($value,$header . $key . " " );
else
print "$header $key2 => $value2\n<br />\n";
}
}

Try loops like this code:
$arrA=array("a", "b", "c");
$arrB=array("x", "y", "z");
$x=array("visitors" => $arrA, "actions" => $arrB);
foreach($x as $key => $value)
{
foreach($value as $v)
echo "$key => $v<br>\n";
}
OUTPUT
visitors => a<br>
visitors => b<br>
visitors => c<br>
actions => x<br>
actions => y<br>
actions => z<br

the best way is var_dump($arr);
<?php
var_dump($_SERVER);
?>
with output that includes types, string length, and will iterate over objects as well.
Since you want to iterate over an array, give foreach a try:
foreach ($arr as $el)
{
// ... Work with each element (most useful for non associative arrays, or linear arrays)
}
// or
foreach ($arr as $key => $value)
{
// ... Work with $key and $value pairs (most useful for hashes/associative arrays)
}

/ / . . . here, we take variable $company for nested array and in this variable we put 2 employee id and its called multi-dimensional array and we take $company variable to assign the associative array with keys so we print the output with keys
$company=[
$emp=[1,"neha","employee",12000,30000],
$emp1=[2,"moni","manager",12000],
];
$company=["first" => $emp,"second" => $emp1];
foreach($company as $key => $value)
{
echo "$key ";
foreach($value as $v1){
echo "$v1";
}
}
output :-
employee ID name designation salary bonus
first 1 neha employee 12000 30000
second 2 moni manager 12000

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.

Accessing nested arrays in PHP without many loops

Consider the following:
$dropdown = array (
"unitofmeasure" => array (
"m" => "meters",
"ft" => "feet"
),
"facing_direction" => array (
"0" => array ("West","North-West","North","North-East","East","South-East"),
"1" => array("South","South-West")
)
....
)
Assume there are n number of sub arrays, not just the two shown above.
Iteration solution:
foreach($dropdown as $key => $val) {
foreach($val as $k => $v) {
foreach($v as $id => $value) {
//manipulate values here
}
}
}
My question is:
is there not a more elegant solution available in PHP?
for example something like foreach($dropdown->children()->children() ...)
I know there are a few semi-similar questions on SO but they're slightly different and the answers are mediocre.
Yes, I personally tend to use array_walk_recursive with a closure(if you're using PHP above 5.3).
You can, obviously, also use recursion if you like getting your hands dirty.
I suppose an example is in order:
$array = [ 0 => [0 => [ 0 => 1 ...]]];
$manipulated_array = [];
array_walk_recursive($array, function($value) use (&$manipulated_array)
{
// do whatever you wish here
});
foreach() just expects an array, so if you only need to iterate ONE of those deeply nested arrays, then you can quite easily have
foreach($arr['level1']['level2'][...]['levelGazillion'] as ...)
I tend to use recursion in these situations:
function modify_array(&$arr)
{
if (is_array(arr)) {
foreach($arr as &$val) {
modify_array($val);
}
} else {
modify_value($arr);
}
}
where modify_value(&$val) is whatever you want to do to each non-array child at any arbitrary depth

Split array into key => array()

Consider the following array:
$array[23] = array(
[0] => 'FOO'
[1] => 'BAR'
[2] => 'BAZ'
);
Whenever I want to work with the inner array, I do something like this:
foreach ($array as $key => $values) {
foreach ($values as $value) {
echo $value;
}
}
The outer foreach-loop is there to split the $key and $value-pairs of $array. This works fine for arrays with many keys ([23], [24], ...)but seems redundant if you know beforehand that $array only has one key (23 in this case). In a case as such, isn't there a better way to split the key from the values? Something like
split($array into $key => $values)
foreach ($values as $value) {
echo $value;
}
I hope I made myself clear.
reset returns the first element of you array and key returns its key:
$your_inner_arr = reset($array);
$your_key = key($array);
Yea, just get rid of your first foreach and define the array you're using with the known $key of your outter array.
foreach ($array[23] as $key =>$val):
//do whatever you want in here
endforeach;
If an array has only one element, you can get it with reset:
$ar = array(23 => array('foo', 'bar'));
$firstElement = reset($ar);
A very succinct approach would be
foreach(array_shift($array) as $item) {
echo $item;
}

PHP array unset string

I am trying to unset a group of array keys that have the same prefix. I can't seem to get this to work.
foreach ($array as $key => $value) {
unset($array['prefix_' . $key]);
}
How can I get unset to see ['prefix_' . $key] as the actual variable? Thanks
UPDATE: The $array keys will have two keys with the same name. Just one will have the prefix and there are about 5 keys with prefixed keys:
Array {
[name] => name
[prefix_name] => other name
}
I don't want to remove [name] just [prefix_name] from the array.
This works:
$array = array(
'aa' => 'other value aa',
'prefix_aa' => 'value aa',
'bb' => 'other value bb',
'prefix_bb' => 'value bb'
);
$prefix = 'prefix_';
foreach ($array as $key => $value) {
if (substr($key, 0, strlen($prefix)) == $prefix) {
unset($array[$key]);
}
}
If you copy/paste this code at a site like http://writecodeonline.com/php/, you can see for yourself that it works.
You can't use a foreach because it's only a copy of the collection. You'd need to use a for or grab the keys separately and separate your processing from the array you want to manipulate. Something like:
foreach (array_keys($array) as $keyName){
if (strncmp($keyName,'prefix_',7) === 0){
unset($array[$keyName]);
}
}
You're also already iterating over the collection getting every key. Unless you had:
$array = array(
'foo' => 1,
'prefix_foo' => 1
);
(Where every key also has a matching key with "prefix_" in front of it) you'll run in to trouble.
I'm not sure I understand your question, but if you are trying to unset all the keys with a specific prefix, you can iterate through the array and just unset the ones that match the prefix.
Something like:
<?php
foreach ($array as $key => $value) { // loop through keys
if (preg_match('/^prefix_/', $key)) { // if the key stars with 'prefix_'
unset($array[$key]); // unset it
}
}
You're looping over the array keys already, so if you've got
$array = (
'prefix_a' => 'b',
'prefix_c' => 'd'
etc...
)
Then $keys will be prefix_a, prefix_c, etc... What you're doing is generating an entirely NEW key, which'd be prefix_prefix_a, prefix_prefix_c, etc...
Unless you're doing something more complicated, you could just replace the whole loop with
$array = array();
I believe this should work:
foreach ($array as $key => $value) {
unset($array['prefix_' . str_replace('prefix_', '', $key]);
}

Iterating over a complex Associative Array in PHP

Is there an easy way to iterate over an associative array of this structure in PHP:
The array $searches has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over $searches[0] through $searches[n], but also $searches[0]["part0"] through $searches[n]["partn"]. The hard part is that different indexes have different numbers of parts (some might be missing one or two).
Thoughts on doing this in a way that's nice, neat, and understandable?
Nest two foreach loops:
foreach ($array as $i => $values) {
print "$i {\n";
foreach ($values as $key => $value) {
print " $key => $value\n";
}
print "}\n";
}
I know it's question necromancy, but iterating over Multidimensional arrays is easy with Spl Iterators
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $key=>$value) {
echo $key.' -- '.$value.'<br />';
}
See
http://php.net/manual/en/spl.iterators.php
Looks like a good place for a recursive function, esp. if you'll have more than two levels of depth.
function doSomething(&$complex_array)
{
foreach ($complex_array as $n => $v)
{
if (is_array($v))
doSomething($v);
else
do whatever you want to do with a single node
}
}
You should be able to use a nested foreach statment
from the php manual
/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}
Can you just loop over all of the "part[n]" items and use isset to see if they actually exist or not?
I'm really not sure what you mean here - surely a pair of foreach loops does what you need?
foreach($array as $id => $assoc)
{
foreach($assoc as $part => $data)
{
// code
}
}
Or do you need something recursive? I'd be able to help more with example data and a context in how you want the data returned.
Consider this multi dimentional array, I hope this function will help.
$n = array('customer' => array('address' => 'Kenmore street',
'phone' => '121223'),
'consumer' => 'wellington consumer',
'employee' => array('name' => array('fname' => 'finau', 'lname' => 'kaufusi'),
'age' => 32,
'nationality' => 'Tonga')
);
iterator($n);
function iterator($arr){
foreach($arr as $key => $val){
if(is_array($val))iterator($val);
echo '<p>key: '.$key.' | value: '.$val.'</p>';
//filter the $key and $val here and do what you want
}
}

Categories