Get array php bigtee - php

I am a stuck with Bigtree.
For my website I need to know a pageID, you can do that using a function.
$nav = $cms->getNavId($path, $previewing = false);
But this is what I get back
string(2) "15" array(0) { } string(0) ""
how can I catch the number (in this case 15)
If I do it this way
$nav = $cms->getNavId($path, $previewing = false);
foreach ($nav as $key) {
echo $key;
}
Then I get this output
15Array

So your loop looks like its doing what you want. If you replaced the echo in the loop with a var_dump it would be more clear.
So to grab the 15; do this:
$nav = $cms->getNavId($path, $previewing = false);
foreach ($nav as $key) {
if( is_numeric($key) ){
$navID = $key;
}
}
var_dump($navID);

Related

PHP Associated Arrays only showing first letter of value

I have a HTML form with multiple inputs.
I have the below php code to get them inputs and put them in an associated array.
However, when dumping the Associated array the value only shows the first letter...
<?php
$valueArray=array
(
"servername"=>'',
"serverlocation"=>'',
"servertype"=>'',
"serverdescription"=>''
);
foreach($valueArray as $key => $value)
{
if (isset($_POST[$key]))
{
$postValue = $_POST[$key];
$actualValue = $postValue;
$valueArray[$key][$value] = $actualValue;
}
}
var_dump($valueArray);
?>
This is what is dumped -
array(4) { ["servername"]=> string(1) "d" ["serverlocation"]=> string(1) "K" ["servertype"]=> string(1) "P" ["serverdescription"]=> string(1) "t" } post
How do i get it to store the whole string, and not just the first letter?
If you want to fill the valueArray with the content of the POST request you have to do this:
$valueArray=array
(
"servername"=>'',
"serverlocation"=>'',
"servertype"=>'',
"serverdescription"=>''
);
foreach($valueArray as $key => $value)
{
if (isset($_POST[$key]))
{
$postValue = $_POST[$key];
$valueArray[$key] = $postValue;
}
}
var_dump($valueArray);
I think you ar wrong with this line:
$valueArray[$key][$value] = $actualValue;
Try this
$valueArray=array
(
"servername"=>'',
"serverlocation"=>'',
"servertype"=>'',
"serverdescription"=>''
);
$postData=array
(
"servername"=>'serverName',
"serverlocation"=>'serverLocation',
"servertype"=>'serverType',
"serverdescription"=>'serverDescription'
);
foreach($valueArray as $key => $value)
{
if (isset($postData[$key]))
{
$postValue = $postData[$key];
$actualValue = $postValue;
$valueArray[$key] = $actualValue;
}
}
var_dump($valueArray);

PHP foreach loops and data retrieval

Using PHP and MySQL I have generated two arrays. I would like to loop through these arrays, retrieve data from both and display together in one sentence.
foreach ($items as $item) {
if(isset($item->item_title)) {
$itemTitle = $item->item_title;
}
// var_dump($itemTitle);
// string(7) "Halfway" string(5) "Story" string(6) "Listen"
}
foreach ($aData["Items"]["Item"] as $a) {
if (isset($a['description'])) {
$aDescription = $a['description'];
}
// var_dump($aDescription );
// string(4) "Good" string(6) "Strong" string(2) "OK"
}
?>
Desired result;
The title is Halfway and the description is Good.
The title is Story and the description is Strong.
The title is Listen and the description is OK.
// etc
// etc
Is it possible to nest the foreach loops, or is there a better more efficient way?
Please try this way. Hope this help!!
foreach ($items as $index => $item) {
if(isset($item->item_title)) {
$itemTitle = $item->item_title;
echo 'The title is '.$itemTitle;
}
if(isset($aData["Items"]["Item"][$index]['description']) {
$itemDescription = $aData["Items"]["Item"][$index]['description'];
echo ' and the description is '.$itemDescription;
}
echo '<br>';
// The title is Halfway and the description is Good.
}
You can merge those two foreach loops using a simple for loop, like this:
$count = count($items) >= count($aData["Items"]["Item"]) ? count($aData["Items"]["Item"]) : count($items);
for($i = 0; $i < $count; ++$i){
if(isset($item[$i]->item_title)) {
$itemTitle = $item[$i]->item_title;
}
if (isset($aData["Items"]["Item"][$i]['description'])) {
$aDescription = $aData["Items"]["Item"][$i]['description'];
}
// your code
}
Sidenote: The above code assumes that two arrays $items and $aData["Items"]["Item"] have unequal number of elements, though this will work for equal number of elements as well. If you're sure that these two arrays will always have equal number of elements, then refactor the $count = ... ; statement in the following way,
$count = count($items);
or
$count = count($aData["Items"]["Item"]);
and use this $count variable in for loop.
Try this hope this will help you out.
Note: Here i am assuming both array's have same indexes.
$items
$aData["Items"]["Item"].
If not you can do array_values($items) and array_values($aData["Items"]["Item"])
foreach ($items as $key => $item)
{
if (isset($item->item_title) && isset($aData["Items"]["Item"][$key]['description']))
{
$itemTitle = $item->item_title;
echo sprinf("The title is %s and the description is %s",$itemTitle,$aData["Items"]["Item"][$key]['description']);
echo PHP_EOL;
}
}

Nested array into menu, but with urls generation

Pleaser help to create menu with nested urls.
I have a mulidimentual array, like this:
["Увлажнение"]=>
array(0) {
}
["Туалетная вода"]=>
array(0) {
}
["Духи и парфюмерная вода"]=>
array(0) {
}
["Мужские аксессуары"]=>
array(13) {
["Часы"]=>
array(1) {
["Часы"]=>
array(0) {
}
}
["Сумки и чехлы"]=>
array(8) {
["Спортивные сумки"]=>
array(0) {
}
["Сумки"]=>
array(0) {
}
["Рюкзаки"]=>
array(0) {
}
I have a function that create HTML Menu from this array:
function makeList($array) {
//Base case: an empty array produces no list
if (empty($array)) return '';
//Recursive Step: make a list with child lists
$output = '<ul>';
foreach ($array as $key => $subArray) {
$url = URLify::filter ($key);
$output .= '<li>' . $key .''. makeList($subArray) . '</li>';
}
$output .= '</ul>';
return $output;
};
That generame manu like:
УвлажнениеТуалетная водаДухи и парфюмерная водаМужские аксессуарыЧасыСумки и чехлыСпортивные сумкиСумки
Every menu urls like:
uvlazhnenie
tualetnaya-voda
duhi-i-parfyumernaya-voda
muzhskie-aksessuary
chasy
But i need urls like:
muzhskie-aksessuary/chasy
With nested (with delemiter) urls.
Please help me. Thanks.
You can use a second argument for your function for this:
function makeList($array, $url = '') {
//Base case: an empty array produces no list
if (empty($array)) return '';
//Recursive Step: make a list with child lists
$output = '<ul>';
foreach ($array as $key => $subArray) {
$url2 = $url . ($url == '' ? '' : '/') . URLify::filter ($key);
$output .= '<li>' . $key .''. makeList($subArray, $url2) . '</li>';
}
$output .= '</ul>';
return $output;
}

Getting Value from array

To get the value from var_dump:
mymeta_url_group =>
0 => string(39) "a:1:{s:10:"mymeta_url";s:8:"You rock";}"
1 => string(40) "a:1:{s:10:"mymeta_url";s:9:"Yeah Sure";}"
I have used:
$urls= get_post_meta( get_the_ID(), 'mymeta_url_group', false );
foreach ( $urls as $url)
{
echo $url["mymeta_url"];
// You Rock
//Yeah Sure
}
Now since I have added repeater and sorter option in backend new var dump shows:
mymeta_url_group =>
0 => string(102) "a:1:{s:10:"mymeta_url";a:2:{s:11:"cmb-field-0";s:8:"You rock";s:11:"cmb-field-1";s:11:"Nope Maybe ";}}"
1 => string(100) "a:1:{s:10:"mymeta_url";a:2:{s:11:"cmb-field-0";s:9:"Yeah Sure";s:11:"cmb-field-1";s:9:"Won't you";}}"
Now How can I get Values "You rock" "Nope Maybe ""Yeah Sure""Won't you" extending my previous solution.
PS if I do var_dump($url["mymeta_url"]);
The output is
Arrayarray(2) { ["cmb-field-0"]=> string(8) "You rock" ["cmb-field-1"]=> string(11) "Nope Maybe " } Arrayarray(2) { ["cmb-field-0"]=> string(9) "Yeah Sure" ["cmb-field-1"]=> string(9) "Won't you" }
I don't know what get_post_meta() is supposed to do, but maybe this will give you some ideas:
<?php
/* Setting up data */
$data = array (
'a:1:{s:10:"mymeta_url";a:2:{s:11:"cmb-field-0";s:8:"You rock";s:11:"cmb-field-1";s:11:"Nope Maybe ";}}',
'a:1:{s:10:"mymeta_url";a:2:{s:11:"cmb-field-0";s:9:"Yeah Sure";s:11:"cmb-field-1";s:9:"Won\'t you";}}'
);
$urls = array();
foreach ($data as $s) {
$urls[] = unserialize ($s);
}
/* Retrieving data */
foreach ($urls as $url) {
foreach ($url['mymeta_url'] as $u) {
echo "$u, ";
}
echo "\n";
}
Here's what I came up with:
foreach($array as $array2) { //If it doesn't work change $array to $array['mymeta_url_group']
$array2 = unserialize($array2);
foreach($array2['mymeta_url'] as $line) {
echo $line; //$line is the sentance you're looking for
}
}
I'm not sure if will work since I had to reconstruct the array from the var_dump() output.

Spread foreach() results over two columns of a table

I'm trying to spread the results of a foreach() loop over two columns of a table (sorry can't post images as this is my first post to stack overflow). I can see where I'm going wrong but haven't a clue how to correct it. I though maybe a next() instead of repeating the foreach() but can't seem to get that to work. Any help would be greatly appreciated.
I need this:
result1 result2
result3 result4
but I'm getting this:
result1 result1
result2 result2
<table>
<?php
foreach ($tags as $tag) {
echo '<tr><td><input name="taga[]" type="checkbox" value="'.$tag->tag.'" id="'.str_replace(" ", "_", $tag->tag).'_id"';
foreach ($search as $searchword) {
if ($searchword == $tag->tag) echo 'checked="checked"';
}
echo ' /><label for="'.str_replace(" ", "_", $tag->tag).'_id">'.$tag->tag.'</label></td>';
next ($tag);
echo '<td><input name="taga[]" type="checkbox" value="'.$tag->tag.'" id="'.str_replace(" ", "_", $tag->tag).'_id"';
foreach ($search as $searchword) {
if ($searchword == $tag->tag) echo 'checked="checked"';
}
echo ' /><label for="'.str_replace(" ", "_", $tag- >tag).'_id">'.$tag->tag.'</label></td></tr>';
}
?>
</table>
You should try to simplify your code when debugging. This would help you isolate the problem and make it easier for communities like StaceOverflow to help you. It looks like this:
<?php
// some fixtures for us to work with
$tags = array('foo', 'bar', 'lolo', );
?>
<pre>
<?php
// your actual issue
foreach ($tags as $tag) {
var_dump( $tag );
next( $tag );
var_dump( $tag );
}
?>
</pre>
You'd see this (wrong) output, which is pretty much the problem you're talking about isn't it ? ;)
string(3) "foo"
string(3) "foo"
string(3) "bar"
string(3) "bar"
string(4) "lolo"
string(4) "lolo"
The signature of next() is:
mixed next ( array &$array )
Which means that it returns a value of any type from an array which is passed by reference. In your case it applies like this:
$tag = next( $tags );
But what happens if you call next() on the last item ?
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
You should break the for loop if next returns false, e.g.:
$tag = next( $tags );
if ( $tag === false ) break;
More elaborated example:
<?php
class Tag {
public $tag;
public function __construct( $tag ) {
$this->tag = $tag;
}
}
$tags = array( );
foreach ( array('foo', 'bar', 'lolo', ) as $word) {
$tags[] = new Tag( $word );
}
$search = array( 'bar', 'the' );
?>
<pre>
<?php
foreach ($tags as $tag) {
var_dump( $tag );
$tag = next( $tags );
if ( $tag === false ) {
break;
}
var_dump( $tag );
}
?>
</pre>
Will output just fine:
object(Tag)#1 (1) {
["tag"]=>
string(3) "foo"
}
object(Tag)#3 (1) {
["tag"]=>
string(4) "lolo"
}
object(Tag)#2 (1) {
["tag"]=>
string(3) "bar"
}
Here's the solution applied to your code (tested/working):
<table>
<?php
foreach ($tags as $tag) {
echo '<tr><td><input name="taga[]" type="checkbox" value="'.$tag->tag.'" id="'.str_replace(" ", "_", $tag->tag).'_id"';
foreach ($search as $searchword) {
if ($searchword == $tag->tag) echo 'checked="checked"';
}
echo ' /><label for="'.str_replace(" ", "_", $tag->tag).'_id">'.$tag->tag.'</label></td>';
$tag = next ($tags);
if ( $tag === false ) {
break;
}
echo '<td><input name="taga[]" type="checkbox" value="'.$tag->tag.'" id="'.str_replace(" ", "_", $tag->tag).'_id"';
foreach ($search as $searchword) {
if ($searchword == $tag->tag) echo 'checked="checked"';
}
echo ' /><label for="'.str_replace(" ", "_", $tag->tag).'_id">'.$tag->tag.'</label></td></tr>';
}
?>
</table>
The php manual for next also includes an important note:
Note: You won't be able to distinguish the end of an array from a
boolean FALSE element. To properly traverse an array which may contain
FALSE elements, see the each() function.
If both columns are exactly the same, or especially if you need more than 2, I recommend this condensed approach (I haven't done a lot of testing on this):
<table>
<tr>
<?php
$count = 0;
$columnCount = 2;
foreach ($interests as $interest) {
if($count++ % $columnCount == 0){
echo "</tr><tr>";
}
echo "<td>$interest->name</td>";
}
while($count++ % $columnCount != 0){
echo "<td> </td>";
}
?>
</tr>
</table>
It will not handle an empty array correctly, so you should add your own code to handle that. You can change columnCount to whatever you want, if you want more than 2 columns.

Categories