create ul and li using a multidimensional array in php - php

I have the following array:
$tree_array
When I do a var_dump, I get:
array(6) {
[0]=> string(23) "$100,000 Cash Flow 2013"
[1]=> array(6) {
[0]=> string(1) "2" ["Goal_ID"]=> string(1) "2"
[1]=> string(13) "Sell Iron Oak" ["Opportunity"]=> string(13) "Sell Iron Oak"
[2]=> string(2) "10" ["OID"]=> string(2) "10"
}
[2]=> array(2) {
[0]=> string(32) "ask her if she would like to buy" ["Activity"]=> string(32) "ask her if she would like to buy"
}
[3]=> array(6) {
[0]=> string(1) "2" ["Goal_ID"]=> string(1) "2"
[1]=> string(8) "Sell Car" ["Opportunity"]=> string(8) "Sell Car"
[2]=> string(2) "11" ["OID"]=> string(2) "11"
}
[4]=> array(2) {
[0]=> string(52) "Call Roy back to see if he would like to purchase it" ["Activity"]=> string(52) "Call Roy back to see if he would like to purchase it"
}
[5]=> array(1) {
["tot_opp"]=> NULL
}
}
My end goal is to create unordered lists and lists (ul, li) with this data. There will be more data added to the array as the database gets updated, so it will keep growing. My goal is to loop through the array and have it create the following code and be able to keep creating lists as the data grows. I am new to php and not sure how to accomplish this.
<ul>
<li>$100,000 Cash Flow 2013</li>
<ul>
<li>Sell Iron Oak</li>
<ul>
<li>ask her if she would like to buy</li>
</ul>
<ul>
<li>Sell Car</li>
</ul>etc...
Any help will be greatly appreciated! Thank you in advance!

You need a recursive function for that, not a loop. This way it will handle any depth of your source array.
function make_list($arr)
{
$return = '<ul>';
foreach ($arr as $item)
{
$return .= '<li>' . (is_array($item) ? make_list($item) : $item) . '</li>';
}
$return .= '</ul>';
return $return;
}
echo make_list($source_array);

Seems like a simple enough recursion to me:
function arrayToList($in) {
echo "<ul>";
foreach($in as $v) {
if( is_array($v)) arrayToList($v);
else echo '<li>' . $v . '</li>';
}
echo "</ul>";
}
It looks like you have some duplicate values up there. Are you using mysql_fetch_array? You should be using mysql_fetch_assoc or mysql_fetch_row depending on whether you need an associative or indexed array.

Related

How to read this array in PHP

I have read other questions regarding reading arrays in PHP and implemented the suggested solutions but these do not seem to work for me...
My array looks like this:-
{
[0]=> array(6)
{ ["name"]=> string(9) "Test04Feb" [0]=> string(9) "Test04Feb"
["paymentvalue"]=> string(6) "500.00" [1]=> string(6) "500.00"
["transactiondate"]=> string(19) "2020-02-05 13:29:37" [2]=> string(19) "2020-02-05 13:29:37"
}
[1]=> array(6)
{ ["name"]=> string(9) "Test04Feb" [0]=> string(9) "Test04Feb"
["paymentvalue"]=> string(7) "1500.00" [1]=> string(7) "1500.00"
["transactiondate"]=> string(19) "1970-01-01 05:30:00" [2]=> string(19) "1970-01-01 05:30:00"
}
[2]=> array(6)
{ ["name"]=> string(9) "Test04Feb" [0]=> string(9) "Test04Feb"
["paymentvalue"]=> string(5) "90.00" [1]=> string(5) "90.00"
["transactiondate"]=> string(19) "2020-02-05 18:12:18" [2]=> string(19) "2020-02-05 18:12:18"
}
}
And none of these work for me:-
$stmt1->execute([$myname]);
$value = $stmt1->fetchAll();
...
foreach ($stmt1 as $row1) {
echo $row1[0]->name;
echo $row1['0']['transactiondate'];
echo $row1[0]['paymentvalue'];
}
Any help would be much appreciated, thank you.
Using
foreach ($stmt1 as $row1) {
$row1 is each individual record from the database. Therefore, rather than having to use [0] as in your code, you should simply be using...
echo $row1->name;
etc.
To check this for yourself, use something like print_r($row1); in the loop to see what each loop has to work with.
In your case $row1 is an array as indicated in your dump. In foreach should use $value and not $stmt. Then:
foreach ($value as $row1) {
echo $row1['name'];
}
P.S. If you want to get only associative keys, use like this:
$value = $stmt1->fetchAll(PDO::FETCH_ASSOC);
Try this if you are using foreach
foreach ($stmt1 as $row1) {
echo $row1['name'];
}
or you can use
echo $stmt1[0]['name'];
Hope this helps you

PHP Multudimensional Array foreach

Using PHP and MySQL, I have generated an array called $response.
A var_dump of $response can be seen here.
array(2) {
["OperationRequest"]=>
array(4) {
["HTTPHeaders"]=>
array(1) {
[0]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(9) "UserAgent"
["Value"]=>
string(14) "ApaiIO [2.1.0]"
}
}
}
["RequestId"]=>
string(36) "f53f381e-efb3-4fef-8e39-4f732b4b463e"
["Arguments"]=>
array(1) {
["Argument"]=>
array(11) {
[0]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(14) "AWSAccessKeyId"
["Value"]=>
string(20) "KEY"
}
}
[1]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(12) "AssociateTag"
["Value"]=>
string(11) "TAG"
}
}
[2]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(6) "IdType"
["Value"]=>
string(4) "ISBN"
}
}
[3]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(6) "ItemId"
["Value"]=>
string(38) "0751538310,9780141382067,9781305341141"
}
}
[4]=>
array(1) {
["#attributes"]=>
array(2) {
["Name"]=>
string(9) "Operation"
["Value"]=>
string(10) "ItemLookup"
}
}.......so on
A json_encode of the array can be seen here (as requested in a comment).
I'd like to select the Title from these two items. From what I can see this is located at;
Items > Item > ItemAttributes > Author
So, using a foreach loop I have tried the following;
foreach ($response as $item) {
echo $item['Items']['Item']['ItemAttributes']['Title']; // line 2
}
However this returns the following error;
Message: Undefined index: Items. Line Number: 2
Where am I going wrong and what must I change in my code in order to achieve the desired result?
Also, any advice on how to 'read' multidimensional arrays would be greatly appreciated.
Thanks
Try this one, it will help you out. You were are iterating on the wrong key that's why you were not getting desired output.
Try this code snippet herefrom json provide by OP in question
foreach($array["Items"]["Item"] as $key => $value)
{
print_r($value["ItemAttributes"]["Title"]);
echo PHP_EOL;
}
Output:
Panic
Panic
Captain Flinn and the Pirate Dinosaurs: Missing Treasure! (Captain Flinn)
For getting unique titles:
foreach(json_decode($json,true)["Items"]["Item"] as $key => $value)
{
$result[]=$value["ItemAttributes"]["Title"];
echo PHP_EOL;
}
print_r(array_unique($result));
#Also, any advice on how to 'read' multidimensional arrays would be greatly appreciated.
Post your encoded json string to
http://json.parser.online.fr
"+" and "-" button at the right panel should help you read it easily.
//Check Items is not empty
if( !isset($response["Items"]["Item"]) || empty($response["Items"]["Item"]) )
throw New Exception("Empty Item");
foreach($response["Items"]["Item"] as $item){
$title = $item['ItemAttributes']['Title']
}
You should debug as:
foreach ($response as $key => $item) {
if(isset($item['Items'])){ //Check Items index defined
echo $item['Items']['Item']['ItemAttributes']['Title'];
}else{
var_dump($key);
}
}

use persistent connection to grab data

Hi all i am grabbing around 1.3k of record from Steam's database and I am wondering how I can speed up my script.
Currently I use file_get_contents on their API url in a loop for each app's ID (so this is sending 1.3k requests which as you can imagine is painfully slow).
Is there a better way? We used to lump all the app's id's together, but they have removed that ability it seems we have to do it one at a time now, and it's not good.
This is my code showing the loop:
foreach($Chunks as $Game)
{
if ($Game['bundle'] == 0)
{
$Subs_URL = 'http://store.steampowered.com/api/packagedetails/?packageids=' . $Game['steam_appid'] .
'&cc=' . $cc . '&filters=basic,price_overview';
if ($JSON = file_get_contents($Subs_URL))
{
$DecodedJson = json_decode($JSON,true);
foreach($Chunks as $Chunk)
{
if (!isset($DecodedJson[$Chunk['steam_appid']]['data']['steam_appid']))
{
$DecodedJson[$Chunk['steam_appid']]['data']['steam_appid'] = $Chunk['steam_appid'];
}
}
//echo '<pre>';
//print_r($DecodedJson);
//print_r(array_keys($DecodedJson));
$GameList = array_merge($GameList,$DecodedJson);
}
else
{
die("Steam API timed out!");
}
}
Here's an example of what $Chunks is:
array(1358) {
[0]=>
array(4) {
["steam_appid"]=>
string(6) "227580"
["name"]=>
string(10) "10,000,000"
["dlc"]=>
string(1) "0"
["bundle"]=>
string(1) "0"
}
[1]=>
array(4) {
["steam_appid"]=>
string(6) "206712"
["name"]=>
string(21) "Cities in Motion: Ulm"
["dlc"]=>
string(1) "1"
["bundle"]=>
string(1) "0"
}
[2]=>
array(4) {
["steam_appid"]=>
string(6) "259620"
["name"]=>
string(24) "3079 -- Block Action RPG"
["dlc"]=>
string(1) "0"
["bundle"]=>
string(1) "0"
}

Array to table HTML output

i have a question here...
i have an array from mysql like this...
array(3) {
[0]=>
array(4) {
["id"]=>
string(1) "1"
["name"]=>
string(8) "Delivery"
["namaShipp"]=>
string(3) "JNE"
["price"]=>
string(5) "30000"
}
[1]=>
array(4) {
["id"]=>
string(1) "3"
["name"]=>
string(12) "Installation"
["namaShipp"]=>
string(7) "Kudamas"
["price"]=>
string(1) "0"
}
[2]=>
array(4) {
["id"]=>
string(1) "5"
["name"]=>
string(12) "Installation"
["namaShipp"]=>
string(5) "MTECH"
["price"]=>
string(1) "0"
}
}
and then i want output it to a simple table.. and i dont know how..
So the result is grouped by ['name'] key.
My question is how to output that array to become like this
-----------------------------
INSTALLATION (get from ['name'])
----------------------------
MTECH - 0 <---- MTECH is get from ['namaShipp'] and 0 is from ['price']
KUDAMAS - 0
-----------------------------
DELIVERY
-----------------------------
JNE - 30000
Anybody can help please?? i will appreciate that..
i've just very confused about thisss...
thanks before
Something like this:
$current=false;
foreach($result as $item)
{
if($item['name']!==$current)
{
echo '
---------------------
'.$item['name'].'
---------------------';
$current=$item['name'];
}
echo '
'$item['namaShipp'].' - '.$item['price'];
}
Try this (assuming your array you showed is $processedArray):
$processedArray = array();
foreach ($mainArray as $innerArray) {
$processedArray[$innerArray['name']][] = $innerArray;
}
foreach ($processedArray as $name => $itemsArray) {
echo '----<br />'.$name.'<br />---';
foreach ($itemsArray as $item) {
echo $item['namaShipp'].' - '.$item['price'].'<br />';
}
}
Transform your array! Create an array of arrays of records:
$list=array();
foreach($data as $item)
$list[$item['name']][]=$item;
foreach($list as $groupname=>$records){
echo '--------------- '.$groupname.' ------------';
foreach($records as $item){
//output one $item as before...
}
}

Wordpress Parsing Array in PHP

How can I parse this in PHP:
a:8:{s:3:"key";s:19:"field_501743d4baa78";s:5:"label";s:8:"Category";s:4:"name";s:8:"category";s:4:"type";s:8:"checkbox";s:12:"instructions";s:0:"";s:8:"required";s:1:"1";s:7:"choices";a:17:{s:4:"Arts";s:4:"Arts";s:8:"Business";s:8:"Business";s:14:"Communications";s:14:"Communications";s:16:"Criminal Justice";s:16:"Criminal Justice";s:13:"Culinary Arts";s:13:"Culinary Arts";s:9:"Education";s:9:"Education";s:11:"Engineering";s:11:"Engineering";s:11:"Health Care";s:11:"Health Care";s:22:"Information Technology";s:22:"Information Technology";s:13:"International";s:13:"International";s:5:"Legal";s:5:"Legal";s:17:"Political Science";s:17:"Political Science";s:10:"Psychology";s:10:"Psychology";s:8:"Religion";s:8:"Religion";s:7:"Science";s:7:"Science";s:9:"Technical";s:9:"Technical";s:10:"Veterinary";s:10:"Veterinary";}s:8:"order_no";s:1:"3";}
to get a list of all the "categorys" such as Arts, Business, Communications etc etc
Thanks for your help
UPDATE
After running unserialize this is what i get:
array(8) { ["key"]=> string(19) "field_501743d4baa78" ["label"]=> string(8) "Category" ["name"]=> string(8) "category" ["type"]=> string(8) "checkbox" ["instructions"]=> string(0) "" ["required"]=> string(1) "1" ["choices"]=> array(17) { ["Arts"]=> string(4) "Arts" ["Business"]=> string(8) "Business" ["Communications"]=> string(14) "Communications" ["Criminal Justice"]=> string(16) "Criminal Justice" ["Culinary Arts"]=> string(13) "Culinary Arts" ["Education"]=> string(9) "Education" ["Engineering"]=> string(11) "Engineering" ["Health Care"]=> string(11) "Health Care" ["Information Technology"]=> string(22) "Information Technology" ["International"]=> string(13) "International" ["Legal"]=> string(5) "Legal" ["Political Science"]=> string(17) "Political Science" ["Psychology"]=> string(10) "Psychology" ["Religion"]=> string(8) "Religion" ["Science"]=> string(7) "Science" ["Technical"]=> string(9) "Technical" ["Veterinary"]=> string(10) "Veterinary" } ["order_no"]=> string(1) "3" }
however i'm not sure how to loop through and just get the category names - sorry - i'm new to PHP - probably just doing something stupid - thanks for your help
That's just a serialized array. Just unserialize it and getting the values is easy:
$array = unserialize(a:8:{s:3:"key";s:19:"field_501743d4baa78";s:5:"label";s:8:"Category";s:4:"name";s:8:"category";s:4:"type";s:8:"checkbox";s:12:"instructions";s:0:"";s:8:"required";s:1:"1";s:7:"choices";a:17:{s:4:"Arts";s:4:"Arts";s:8:"Business";s:8:"Business";s:14:"Communications";s:14:"Communications";s:16:"Criminal Justice";s:16:"Criminal Justice";s:13:"Culinary Arts";s:13:"Culinary Arts";s:9:"Education";s:9:"Education";s:11:"Engineering";s:11:"Engineering";s:11:"Health Care";s:11:"Health Care";s:22:"Information Technology";s:22:"Information Technology";s:13:"International";s:13:"International";s:5:"Legal";s:5:"Legal";s:17:"Political Science";s:17:"Political Science";s:10:"Psychology";s:10:"Psychology";s:8:"Religion";s:8:"Religion";s:7:"Science";s:7:"Science";s:9:"Technical";s:9:"Technical";s:10:"Veterinary";s:10:"Veterinary";}s:8:"order_no";s:1:"3";});
var_dump($array);
$sample_arr = unserialize($array); //unserialize here
$sample_arr = $sample_arr['choices']; //get the array
then you have the category list saved to $sample_arr.
foreach($sample_arr as $temp) {
//do stuff with each element here
}
Examples include outputting this as a html list
echo '<ul>';
foreach($sample_arr as $temp) {
echo '<li>' . $temp . '</li>';
}
echo '</ul>';

Categories