After searching for an answer in this forum I found only related questions but under other context that would not apply to my case. Here's my problem:
I have a 3-dim array defined in a function like this:
$m_Array[h][$family][$iterator]
the values for
$family range from 6-10;
$iterator from 0-3 but has duplicates (0,1,2,3,1),
and the $m_Array results in values (25,26,30,31,33).
I am unable to echo the result using those indices to get these results once returned from the function.
NOTE: I was able to echo when I had 2-dim $m_Array[h][$iterator] but could not use it because the last value for the iterator would replace the second in the array.
Since I was able to echo the 2-dim, this is not a question on getting the return from the function or iterate over the indices.
Thanks.
Use print_r($arrayName) to print an array. You cannot echo an Array or Object
as others mentioned, you can use var_dump() or print_r(). If you need to access each item then you're going to need nested loops.
foreach($m_Array as $i => $h)
{
//echo $i, $key for h
foreach($h as $j => $family)
{
//echo $j, key for family
foreach($family as $k => $iterator)
{
echo $iterator;
}
}
}
try this:
$keys = array_keys($h);
for($i = 0; $i < count($h); $i++) {
echo $keys[$i] . "{<br>";
foreach($h[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
}
echo "}<br>";
}
It prints all values and keys
Related
This question already has answers here:
PHP highlight duplicate values in array [duplicate]
(2 answers)
Closed last month.
I have a array that i want to check if has duplicates using PHP
$i=array('One','Two','Two','Three','Four','Five','Five','Six');
I was able to achieve it by using below function
function array_not_unique($input) {
$duplicates=array();
$processed=array();
foreach($input as $i) {
if(in_array($i,$processed)) {
$duplicates[]=$i;
} else {
$processed[]=$i;
}
}
return $duplicates;
}
I got below output
Array ( [0] => Two [1] => Five )
Now how can i display the previous arrays and mark values with duplicates referencing the array_not_unique function return values to a HTML table.
My goal is to display the duplicated values with red font color.
Try this piece of code... simplest and shortest :)
$i=array('One','Two','Two','Three','Four','Five','Five','Six');
$arrayValueCounts = array_count_values($i);
foreach($i as $value){
if($arrayValueCounts[$value]>1){
echo '<span style="color:red">'.$value.'</span>';
}
else{
echo '<span>'.$value.'</span>';
}
}
Here is optimized way that will print exact expected output.
<?php
$i=array('One','Two','Two','Three','Four','Five','Five','Six');
$dups = array_count_values($i);
print_r($dups);
foreach($i as $v)
{
$colorStyle = ($dups[$v] > 1) ? 'style="color:red"' : '';
echo "<span $colorStyle>$v</span>";
}
?>
Try this,
function array_not_unique($input) {
$duplicates=array();
$processed=array();
foreach($input as $key => $i) {
if(in_array($i,$processed)) {
$duplicates[$key]=$i; // fetching only duplicates here and its key and value
}
}
return $duplicates;
}
foreach($processed as $k => $V){
if(!empty($duplicates[$k])){ // if duplicate found then red
echo '<span style="color:red">'.$duplicates[$k].'</span>';
}else{
echo '<span>'.$duplicates[$k].'</span>'; // normal string
}
}
Like this :
PHP
function array_duplicate_css($input) {
$output = $processed = array();
foreach($input as $key => $i) {
$output[$key]['value'] = $i;
if(in_array($i, $processed)) {
$output[$key]['class'] = 'duplicate';
} else {
$output[$key]['class'] = '';
$processed[] = $i;
}
}
return $output;
}
foreach(array_duplicate_css($input) as $row) {
echo '<tr><td class="' . $row['class'] . '">' . $row['value'] . '</td></tr>';
}
CSS
.duplicate {
color: #ff0000;
}
Simple use array_count_values.
$array=array('One','Two','Two','Three','Four','Five','Five','Six');
$new_array= array_count_values($array);
foreach($new_array as $key=>$val){
if($val>1){
for($j=0;$j<$val;$j++){
echo "<span style='color:red'>".$key."</span>";
}
}else{
echo "<span>".$key."</span>";
}
}
It can be done in several ways. This is just a one method. Step one maintain 2 arrays. Then store the duplicated indexes in one array. When you iterating use a if condition to check whether the index is available in the "duplicated indexes" array. If so add the neccessary css.
I have an array like this $arr = Array ("A","E","I","O","U");
My question is using implode function how can I make the output like this
1.A
2.E
3.I
4.O
5.U
You need to iterate over each values like this:
$arr = array("A","E","I","O","U");
foreach ($arr as $key => $value) {
echo $key + 1 . ".{$value} <br>";
}
This will give you the desired Output as:
1.A
2.E
3.I
4.O
5.U
Hope this helps!
$i = 1;
foreach ($arr as $v) {
echo $i . '.' . $v . '<br>';
$i++;
}
no need to use implode function. Just use foreach loop to iterate whole array.
use array_walk to traverse the array like this:
array_walk($array, function($v, $k)
{
echo $k + 1 . '.' . $v . "<br>";
});
I have a bug in my code but the solution is buried deep in a JSON return
https://api.instagram.com/v1/users/self/media/liked?access_token=207436640.c57b856.b0a8944d1e0c4e70a6ec581679c656b5
There are array[17] I must loop through
foreach ($arr['data'][0]['likes']['data'] as $liker){
echo '<img src="'.$liker['profile_picture'].'" /></br>';
echo '<p> '.$liker['username'].'</p></br>';
}
Works fine for one, but
for($i = 0; $i < sizeof($arr['data'][]); $i++){
echo '<img src="'.$arr['likes']['data']['profile_picture'].'" /></br>';
echo '<p> '.$liker['username'].'</p></br>';
}
has less than desirable results.
Fatal error: Cannot use [] for reading in /var/www/localhost/htdocs/instagram2.php on line 68
or if I remove the [], I get 'undefined 'likes'.
How do I properly loop through a JSON subarray?
You way of approaching the for compared to the foreach is wrong. In the foreach the current item during the iteration is automatically assigned to $liker, however nothing like this occurs in the for. You are only incrementing the value of $i.
/// #shaddy has said, this is the correct way to access the array size
/// it is more optimal to calculate it outside of the loop.
$len = sizeof($arr['data']);
/// with a for loop, you have to use $i to calculate the item
for($i = 0; $i < $len; $i++){
$item = $arr['data'][$i];
/// and then access each of the subitems inside $item
...
}
But you also have other problems. You are seemingly trying to output the image of each of the profile_pictures for the likers; but this is also an array of data. In your first example you are directly stepping through this array, so everything works. In your second however you are only looping the container array, and not the list of likers. To get this to work you must have a second loop:
$len = sizeof($arr['data']);
/// with a for loop, you have to use $i to calculate the item
for($i = 0; $i < $len; $i++){
$item = $arr['data'][$i];
/// best to check for existence before accessing to avoid errors
if ( !empty($item['likes']['data']) ) {
$likers = $item['likes']['data'];
$len2 = sizeof($likers);
/// step each of the likers
for($k = 0; $k < $len2; $k++){
$liker = $likers[$k];
if ( !empty($liker['profile_picture']) ) {
echo '<img src="'.$liker['profile_picture'].'" /></br>';
}
/// the username field is also part of the user array inside item
if ( !empty($liker['username']) ) {
echo '<p> '.$liker['username'].'</p></br>';
}
}
}
}
However the above all looks quite complicated, I usually don't use for loops in php, foreach has a much nicer interface to work with, and is designed to work with arrays:
foreach ( $arr['data'] as $i => $item ) {
if ( !empty($item['likes']['data']) ) {
foreach ( $item['likes']['data'] as $k => $liker ) {
if ( !empty($liker['profile_picture']) ) {
echo '<img src="' . $liker['profile_picture'] . '" /></br>';
}
if ( !empty($liker['username']) ) {
echo '<p> ' . $liker['username'] . '</p></br>';
}
}
}
}
Of course you may just have been wanting to loop through the likers array just like in your first example, to do that with a for you just need:
$likers = $arr['data'][0]['likes']['data'];
$len = sizeof($likers);
for( $i = 0; $i < $len; $i++ ){
echo '<img src="' . $likers[$i]['profile_picture'] . '" /></br>';
echo '<p> ' $likers[$i]['username'] . '</p></br>';
}
please note:
There is also another caveat to be aware of, and this will cause some of the above snippets to fail if it is not true. All the above code is always working with arrays, and so the $arr array must only contain arrays. However your dataset shows a mixture of arrays and objects. When dealing with objects in PHP you need to use a different accessor.
As I am unable to see how you are loading your JSON it is difficult to advise, as depending on the manner objects can be converted into arrays. All your examples have been treating every part of your structure as an array, and that is why I have assumed the same in the above.
However the standard way would be to use json_decode which would/should preserve the array/object difference by default. This means where ever there is an object you will need to use $obj -> prop rather than $obj['prop'], so my preferred example above would look like this:
foreach ( $arr['data'] as $i => $item ) {
if ( !empty($item->likes['data']) ) {
foreach ( $item->likes['data'] as $k => $liker ) {
if ( !empty($liker->profile_picture) ) {
echo '<img src="' . $liker->profile_picture . '" /></br>';
}
if ( !empty($liker->username) ) {
echo '<p> ' . $liker->username . '</p></br>';
}
}
}
}
Also if you prefer working just with arrays, you could use something like this:
https://coderwall.com/p/8mmicq/php-convert-mixed-array-objects-recursively
Well $arr['data'][] is invalid way to reference the data value of the array the correct one is $arr['data']
for($i = 0; $i < sizeof($arr['data']); $i++){
foreach ($arr['data'][$i]['likes']['data'] as $liker) {
echo '<img src="'.$liker['profile_picture'].'" /></br>';
echo '<p> '.$liker['username'].'</p></br>';
}
}
You can read more about arrays here http://php.net/manual/en/language.types.array.php .
I'm trying to read an array to save some values but it doesnt work! Here's my code:
$array=$_POST['idprod'];//I get my array and save it on a var
print_r($array); //It has ALL the data (I use a print_r($array); And YES!! It has the information i need)
$ids[]=explode(',',$array);//Substring to my var
for( $contador=0; $contador <count($ids); $contador++ )
{
echo $ids[$contador].'<br/>';
}
It shows me Array to string conversion in...
What could I do?
use foreach Instead for loop
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
foreach ($array => $var ) {
// do any thing
}
replace
$ids[]=explode(',',$array);//Substring to my var
for( $contador=0; $contador <count($ids); $contador++ ) {
echo $ids[$contador].'<br/>';
and set
$ids = explode(',',$array);
foreach($ids as $id) {
echo $id ."<br>";
}
You only need to explode(), if the incomming data is a comma separated string.
$string = $_POST['idprod'];
$array= explode(',', $string); // split the comma separated values into an array
for($i=0; $i<count($array); $i++)
{
echo $array[$i] . '<br/>';
}
Else you can directly work with the incomming array:
$array = $_POST['idprod'];
for($i=0; $i<count($array); $i++)
{
echo $array[$i] . '<br/>';
}
I have two array output (using preg_match_all), for example: $name[1] and $family[1].
i need to put these arrays together, and i use foreach as this:
foreach( $name[1] as $name) {
foreach( $family[1] as $family) {
echo $name.$family.'<br />';
}
}
but it don't work.
(each foreach loop works separately)
Assuming they have matching keys for the loop:
foreach( $name as $key => $value) {
echo $value[$key] . $family[$key] . '<br />';
}
This will go through each match for $name and print it out, and then print out the corresponding $family with it. I don't think you want to hardcode [1].
If you do, I'm a little confused and would like to see a var_dump of both $name and $family for clarification.
$together= array();
foreach( $name as $key => $n) {
$tuple= array('name'=>$name[$key],'family'=>$family[$key]);
$together[$key]= $tuple;
}
foreach( $together as $key => $tuple) {
echo "{$tuple['name']} {$tuple['family']}<br />";
}
Use array_combine():
Creates an array by using the values from the keys array as keys and
the values from the values array as the corresponding values.
PHP CODE:
$nameFamilly=array_combine($name[1] , $family[1]);
foreach( $nameFamilly as $name=>$familly) {
echo $name.$family.'<br />';
}