a very hard result to foreach in php - php

$content is an arry. when i print_r($content) the result is too long. now i
echo $fenlei=$content['body']['#object']->field_fenlei['zh-hans'][0]['taxonomy_term']->name;
the result of $fenlei is java. but there maybe many values of $fenlei. eg:
$content['body']['#object']->field_fenlei['zh-hans'][0]['taxonomy_term']->name;
$content['body']['#object']->field_fenlei['zh-hans'][1]['taxonomy_term']->name;
$content['body']['#object']->field_fenlei['zh-hans'][2]['taxonomy_term']->name;
......
how to loop out the
$content['body']['#object']->field_fenlei['zh-hans'][1]['taxonomy_term']->name;
$content['body']['#object']->field_fenlei['zh-hans'][2]['taxonomy_term']->name;
value. it too hard for me. :)

You can store the common code and foreach next:
$common = $content['body']['#object']->field_fenlei['zh-hans'];
foreach($common as $key => $value){
echo "{$key}: " . $value['taxonomy_term']->name;
}

If you want to print out large arrays that are difficult to read you can try:
echo '<pre>'.print_r($array, true).'</pre>';
It makes arrays a little more pretty.

Related

Echo an Array and make the content look pretty on the page

I am trying to echo out my array on each line, not bunched together.
I have tried <br />, this only show's on the front end, but when you look at HTML code. Its still clumped together.
$arrays = [];
$arrays[] = "Good";
$arrays[] = "Bad";
foreach ($arrays as $array){
echo $array;
}
Result:
GoodBad
Want Result:
Good
Bad
Short of using print_r, to quickly get your desired result, just make this small change:
echo $array."\n";
Make sure it's double-quotes and it will add a new line.
(That would do what "<br />" does on HTML)
Try using print_r($arrays). docs here.
Try echo "<pre>; var_dump($arrays); echo "</pre>;

Loop through each element under "Data"

I'm using Kucoin's API to get a list of coins.
Here is the endpoint: https://api.kucoin.com/v1/market/open/coins
And here's my code:
$kucoin_coins = file_get_contents('https://api.kucoin.com/v1/market/open/coins');
$kucoin_coins = json_decode($kucoin_coins, true);
print_r($kucoin_coins);
I can see how to target one coin like so:
echo "name: " . $kucoin_coins['data'][0]['name'];
But I can't see how to loop through them.
How can I loop through each of the "coins" returned here? They are under the "data" part that is returned. I'm sorry, I'm just not seeing how to do it right now. Thank you!
You can loop through the decoded elements using the foreach command:
foreach ($kucoin_coins['data'] as $coin) {
//do your magic here.
}
But I usually prefer using json_decode($kucoin_coins) rather than the one for arrays. I believe this:
$item->attribute;
Is easier to write than this one:
$item['attribute'];
foreach($kucoin_coins['data'] as $data) {
echo $data['name']."\n";
}
You can loop through your data using foreach() like this
<?php
$kucoin_coins = file_get_contents('https://api.kucoin.com/v1/market/open/coins');
$kucoin_coins = json_decode($kucoin_coins, true);
print '<pre>';
print_r($kucoin_coins);
print '</pre>';
foreach($kucoin_coins['data'] as $key=>$value){
echo $value['name']. "<br/>";
}
?>
See DEMO: http://phpfiddle.org/main/code/q6kt-dctg

How Can I Pull An Entire Result From A Foreach Loop

I want to get the result from a foreach loop, but use it outside of the foreach brackets. What is the easiest way to do this.
Currently the below is working fine:
foreach($esmc->find('p') as $paragraph){
$showparag = $paragraph->innertext. '<br/>';
echo $showparag;//Will show result of array
}
However, I would like to have this so I can add text to it (echo is outside of foreach brackets):
foreach($esmc->find('p') as $paragraph){
$showparag = $paragraph->innertext. '<br/>';
}
echo "This shows results of array as $showparag";//Contains text + array
Currently if I do the second example, it is only returning the final record in the array.
Any help would be greatly appreciated.
$string = 'This shows results of array as ';
foreach($esmc->find('p') as $paragraph){
$showparag = $paragraph->innertext. '<br/>';
$string .= $showparag;
}
echo $string;
http://php.net/manual/en/language.variables.scope.php
P.S. Despite there is a lot examples of global variables usage in the manual, you actually should not use it as it is considered as a bad practice.
Your questions is rather vague, if this isn't what you want, can you please clarify in the comments.
This, however should generate a string for you to print all of the results as one string, outside of the foreach loop.
$showparag
foreach($esmc->find('p') as $paragraph){
$showparag .= $paragraph->innertext. '<br/>';
}
echo "This shows results of array as $showparag";//Contains text + array

Print out large JSON_DECODE object in meaningful manner?

I'm working on a website that I make heavy use of json objects. I have a very, very large json object that contains, from what it looks like, dozens of arrays of arrays of arrays of etc...
I've been doing my normal method of just doing:
$obj = json_decode($json,true);
if( $obj == NULL )
echo "JSON NULL!<br>";
else{
echo "here!!<br>";
foreach( $obj as $key=>$val ){
foreach( $val as $k=>$v){
echo "$k <br>";
}
}
}
But the output is not very meaningful and I find it hard to tell what is the parent of what in terms of being able to access the individual items in a $obj["one"]["two"]["three]" manner.
I've looked around quite a bit and there are many examples of using json_decode in foreach arrays, but all the examples I've found target single-depth arrays. Does anyone know of a way to output the contents in a way that would make it easier to tell what contains what?
Ideally something that tabbing, that's the most visually understandable.
Thanks!
Edit: Thanks for the fast replies! I didn't know about the tags. I wish I could select all of them as "best answer"!
$obj = json_decode($json,true);
echo "<pre>".htmlspecialchars(print_r($obj,TRUE))."</pre>\n";
I agree. This might look good to read
$obj = json_decode($json,true);
echo "<pre>";
print_r( $obj );
echo " </pre>";
This also does the indenting.
I'd suggest something like:
$obj = json_decode($json, true);
echo '<pre>';
echo print_r($obj, true);
echo '</pre>';
I guess you have problem with not knowing how many levels of arrays you have.
You could do a recursive function like this:
function echoarray($obj, $i = 0){
foreach($obj as $key => $val){
if(isarray($val)) echoarray($val, $i++);
else echo "$i - $key: $val <br/>";
}
}
Instead of your original foreach. Variable $i can tell you what level are you on currently.
Take this not as a finished code but as a concept, if it suits your needs.
Basically if current $val is array, function echoarray is called again and again, until $val isn't an array anymore.

How to print out the keys of an array like $_POST in PHP?

Maybe the code looks like something like this:
foreach(...$POST){
echo $key."<br/>;
}
var_dump($_POST);
or
print_r($_POST);
You might insert a pre tag before and after for the clearer output in your browser:
echo '<pre>';
var_dump($_POST);
echo '</pre>';
And I suggest to use Xdebug. It provides an enchanted var_dump that works without pre's as well.
See the PHP documentation on foreach:
http://php.net/manual/en/control-structures.foreach.php
Your code would look something like this:
foreach ($_POST as $key=>$element) {
echo $key."<br/>";
}
Tested one liner:
echo join('<br />',array_keys($_POST));
If you want to do something with them programmatically (eg turn them into a list or table), just loop:
foreach ($_POST as $k => $v) {
echo $k . "<br>";
}
For debugging purposes:
print_r($_POST);
or
var_dump($_POST);
And if you want full coverage of the whole array, print_r or even more detailed var_dump
$array = array_flip($array);
echo implode('any glue between array keys',$array);
Or you could just print out the array keys:
foreach (array_keys($_POST) as $key) {
echo "$key<br/>\n";
}
Normally I would use print_r($_POST).
If using within an HTML page, it's probably worth wrapping in a <pre> tag to get a better looking output, otherwise the useful tabs and line breaks only appear in source view.
print_r() on PHP.net

Categories