PhP howto sizeof(JSON:array[]) - php

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 .

Related

Add new data in foreach loop multidimensional array

I try to add new data in a multidimensional array for each loop, but it wont work.
This shows the values in my array:
$keys = array_keys($klanten);
for($i = 0; $i < count($klanten); $i++) {
foreach($klanten[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
$klanten['newData'] = 'test';
}
}
With $klanten['newData'] = 'test'; I try to add "test" to each array, but it won't work.
I also tried to use this, AFTER the script above:
foreach ($klanten as &$item ){
$item['newData'] = 'test';
}
That will work, but I think there must be an option to do it in the foreach loop above the first time. How can I do that?
Hi so you got most of it right but, you see when you are looping around a variable and adding a new item in it you have to make sure to give a index for that new array index so...
$keys = array_keys($klanten);
for($i = 0; $i < count($klanten); $i++) {
foreach($klanten[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
// $klanten['newData'] = 'test'; // instead of this
$klanten[$key]['newData'] = 'test'; // do this
}
}
This will save each and every value of newData index according to its key in $klanten array.

PHP How to echo a 3-dim array

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

for loop append variable php

I have a xml file that i want to echo to the browser
echo $rule = $info->rule1
echo $rule = $info->rule2
Result:
example 1
example 2
Because the rule in the xml is dynamic i want to count how much rules there are and pass that variable behind the "rule"
$xml = simplexml_load_file('file.xml');
$xml_nested = $xml->monthlegenda;
echo "<ul>";
foreach ($xml_nested as $info):
for($i=1; $i < count($info); $i++){
$rule = $info->rule;
$rule .= $i;
echo $rule;
};
endforeach;
echo "</ul>";
As a result i expect:
example 1
example 2
but i get
12
You're probably looking for a way to get the property of an object from a string, which is done like so:
$instance->{$var.'string-part'.$otherVar};
In your case, that'd be:
echo $info->{'rule'.$i};
For more details, refer to the man pages on variable variables. Especially the section entitled " #1 Variable property" should be of interest to you...
But since you're echoing <ul> tags before and after the loop, I'm assuming you're trying to create a list, in which case, your echo statement should look like this:
echo '<li>', $info->{'rule'.$i}, '</li>';//comma's not dots!
Note that you'll never loop through the entire $info object, because of your for loop. You should either write:
for ($i=1,$j = count($info);$i<=$j;$i++)
{
echo $info->{'rule'.$i};
}
Note that I'm assigning count($info) to a variable, to avoid calling count on each iteration of the loop. You're not changing the object, so the count value will be constant anyway... or simply use foreach:
foreach($info as $property => $val)
{//val is probably still an object, so use this:
echo $info->{$property};
}
In the last case, you could omit the curlies around $property, but that's not recommended, but what you can do here, is check if the property concerned is a rule property:
foreach($info as $property => $val)
{
if (substr($property, 0, 4) === 'rule')
{//optionally strtolower(substr($property, 0, 4))
echo '<li>', $info->{$property}, '<li>';
}
}
That's the easiest way of doing what you're doing, given the information you've provided...
Try this code for "for":
for($i=1; $i < count($info); $i++)
{
$rule = $info->{'rule'.$i};
echo $rule;
}
Try this one:
$rule = $info->{rule.$i};
Check this
$xml = simplexml_load_file('file.xml');
$xml_nested = $xml->monthlegenda;
echo "<ul>";
foreach ($xml_nested as $info)
for($i=1; $i < count($info); $i++){
$rule = "";
$rule = $info->rule;
$rules = $rule.$i;
echo $rules;
}
echo "</ul>";

How to display two arrays in one foreach loop?

am storing two arrays in one column.first one is images stored as image1*image2*...etc and second one is descriptions as description1*description2*...etc. i want to use these two set of arrays in one foreach loop.Please help.
Just reference the key:
foreach ($images as $key => $val) {
echo '<img src="' . $val . '" alt="' . $descriptions[$key] . '" /><br />';
}
You can't use foreach, but you can use for and indexed access like so.
$count = count($images);
for ($i = 0; $i < $count; $i++) {
$image = $images[$i];
$description = $descriptions[$i];
}
You could use array_combine to combine the two arrays and then use a foreach loop.
$images = array('image1', 'image2', ...);
$descriptions = array('description1', 'description2', ...);
foreach (array_combine($images, $descriptions) as $image => $desc) {
echo $image, $desc;
}
It does not seem possible by foreach loop. Instead try using for loop. If you are sure both your arrays are of the same size, then try using following code:
for ($i=0; $i<sizeof(array1); $i++) {
echo $arrray1[$i];
echo $arrray2[$i];
}

Parent-child navigation generation from tree array in PHP

Following function arranges the array totally wrong. Have you noticed any wrong piece of code in following function?
function buildHtmlList($array)
{
$maxlevel = 0;
foreach ($array as $key => $value)
{
$previousparent = isset($array[$key - 1]['parent']) ? $array[$key - 1]['parent'] : null;
$nextparent = isset($array[$key + 1]['parent']) ? $array[$key + 1]['parent'] : null;
if ($value['parent'] != $previousparent)
{
echo "\n<ul>";
++$maxlevel;
}
echo "\n<li>" . $value['name'];
if ($nextparent == $value['parent'])
echo "</li>";
}
for ($i = 0; $i < $maxlevel; ++$i)
{
echo "\n</li>\n</ul>";
}
}
It arranges the array totally wrong. Have you noticed any wrong piece of code in following function?
The wrong piece is the whole logic of the function. You treat the array as a flat list (as it is!), however, you'd like to display a tree.
As a flat list can't be displayed as a tree, you need to change the flat list to a tree first and then write a function that displays a tree.
An example how to convert a flat array to a tree/multidimensional one is available in a previous answer.
Try something like this (where $array is formatted like your example):
$corrected_array = array();
// This loop groups all of your entries by their parent
foreach( $array as $row)
{
$corrected_array[ $row['parent'] ][] = $row['name'];
}
// This loop outputs the children of each parent
foreach( $corrected_array as $parent => $children)
{
echo '<ul>';
foreach( $children as $child)
{
echo '<li>' . $child . '</li>';
}
echo '</ul>';
}
Demo

Categories