Is there a better solution than this to print the results - php

<?php
$arr =
[
'name' => 'hussin' ,
"age" => 25,
'job' =>
[
'php', 'ajax'
]
];
foreach ($arr as $key => $value)
{
if(!is_array($arr[$key]))
echo $key .' '. $value."<br>";
else
foreach ($arr['job'] as $key => $value)
echo $key .' '. $value."<br>";
}
?>
result
name Hussien
age 27
0 php
1 ajax
Is there a better solution than this to print the results?
I have an associative array with regular data, including a array type, which is the best solution for accessing all data

I may be misunderstanding, but I think you're looking for a recursive algorithm:
function printAll(array $arr){
foreach($arr as $k => $v){
if(is_array($v)){
return printAll($v);
}
print $k . ":" . $v . "\r\n";
}
}
printAll(['name' => 'hussin' ,"age" => 25,'job' => ['php', 'ajax']]); // name:hussin age:25 0:php 1:ajax
Now, this can of course be improved to deal with other iterables and the nested array keys, but hopefully you get the jist.

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.

Get foreach numeric index when keys are named

This question is just for fun and out of curiosity.
Edit : My question is different than
How to find the foreach index
Because $key has already a non-numeric value in my case.
Without having a variable outside a foreach that is increment inside the foreach scope, as the usual $i, is there a way to get the index of an item when $key is already named ?
Exemples :
$myNumericIndexArray = ('foo', 'bar', 'go', 'habs');
foreach($myNumericIndexArray as $key => $value){
//Here $key will be 0 -> 1 -> 2 -> 3
}
Now, if I have :
$myNamedIndexArray = ('foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic');
foreach($myNamedIndexArray as $key => $value){
//Here $key will be foo -> go -> CSGO_bestTeam
}
Can I, without having to :
$i=0;
foreach($myNamedIndexArray as $key => $value){
//Here $key will be foo -> go -> CSGO_bestTeam
$i++;
}
access the index of a named array. Something declared in the foreach declaration like in a for or a status of $key ?
Have a good one.
If you really want index array of associative array than try this:
$myNamedIndexArray = ['foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic'];
$keys = array_keys($myNamedIndexArray);
foreach($myNamedIndexArray as $key => $value){
echo array_search($key, $keys);
}
I don't know why you would want to do an array_keys() and array_search() every loop iteration. Just build a reference array and you can still foreach() the original:
$positions = array_flip(array_keys($myNamedIndexArray));
foreach($myNamedIndexArray as $key => $value){
echo "{$key} => {$value} is position {$positions[$key]}\n";
}
Something like this :
<?php
$myNamedIndexArray = array('foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic');
$numericIndexArray = array_keys($myNamedIndexArray);
foreach($numericIndexArray as $key=>$value){
echo $key.'</br>'; //here key will be 0 1 2
echo $value. '</br>';
}
I'd try something like this:
<?php
$myNamedIndexedArray = ['foo' => 'bar', 'go' => 'habs', 'CSGO_bestTeam' => 'fnatic'];
$myNumberIndexedArray = array_keys($myNamedIndexedArray);
foreach($myNumberIndexedArray as $key => $value){
echo $key. " => " . $myNamedIndexedArray[$myNumberIndexedArray[$key]]."<br />";
}
?>
Adn the output will be:
0 => bar
1 => habs
2 => fnatic

I can't compare associative array indexes to a var

I can not figure out how to compare the array index. I know this has to be simple.
$list_array array (
'first' => array('one' => 1, 'two' => 2),
'second' => array('one' => 3, 'two' => 4)
);
foreach ($list_array as $key) {
if(<the-list_array-index> == 'second' ) {
echo $key['one']. ' - '. $key['two'];
}
}
result 3 - 4
Use this syntax:
foreach ($array as $key => $value)
foreach ($list_array as $index => $key) {
if($index == 'second' ) {
echo $key['one']. ' - '. $key['two'];
}
}
One suggestion though: Rename $key to an appropriate and meaningful name in your context!
If you do not find any or if your function works with arrays in general, use $value since this term is very well-known among developers:
foreach ($list_array as $index => $value) {
if($index == 'second') {
echo $value['one'] . ' - ' . $value['two'];
}
}
Consider u_mulder's answer below if you just want to directly access the key. As far as I can see in your code, a loop is unnecessary.
if (array_key_exists('second', $list_array))
echo $list_array['second']['one'] . ' - ' . $list_array['second']['two'];

Array ksort only shows non-like values?

Have an array for a ranking script.
Some times the key will be the same. They are numeric.
When the sort is ran, only non-like values are echoed.
Can't figure out the fix.
$list = array( $value1 => 'text', $value2 => 'text', $value3 => 'text');
krsort($list);
foreach ($list as $key => $frame) {
echo $frame;
}
If you assign two values to the same key in an array, the first value will be overridden by the second. You'll therefore end up with only one value for that key in the array.
To resolve this, I'd suggest to change your array structure like this:
<?php
$list = array( $key1 => array($key1member1, $key2member2),
$key2 => array($key2member1),
$key3 => array($key3member1, $key3member2, $key3member3) );
krsort($list);
foreach ($list as $key => $frames) {
foreach ($frames => $frame) {
echo $frame;
}
}
?>
Going by what you wrote in the comments to this question and my other answer, I'd recommend to switch keys and values.
<?php
$list = array( "frame1" => 4, "frame2" => 2, "frame3" => 99, "frame4" => 42 );
arsort($list);
foreach ($list as $frame => $ranking) {
echo $frame;
}
?>

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