array variable index in that rare SimpleXML functions - php

I have a label on a form select and I get that value with $ _POST like this:
$gallery = array($_POST['gallery']);
and that value will put it here:
$image = $sitemap->gallery[$gallery]->addChild('image');
the problem is giving me error is as follows:
Fatal error: Call to a member function addChild() on a non-object in
I do not understand is that if I put a value directly asin me do it like so:
$gallery = 0;
$Image = $sitemap->gallery[$gallery]->addChild('image');
I do well, what happens is that I want the user to choose,
Kind of strange as it may fix.

Understanding Arrays:
$gallery = array($_POST['gallery']);
echo "Gallery Array: <pre>".print_r($gallery,true)."</pre><br />";
Output:
Array
(
[0] => 'value in array'
)
How to get the value out of an array:
echo "Get Array Value: ".$gallery[0]."<br />"; // You should be displaying the array index 0
Adding a custom index
$gallery = array('gallery' => $_POST['gallery']);
echo "Gallery Array: <pre>".print_r($gallery,true)."</pre><br />";
Output:
Array
(
[gallery] => 'value in array'
)
Getting the value from the customer index array
echo "Get Array Value: ".$gallery['gallery']."<br />"; // You should be displaying the array index gallery

use this:
$gallery = $_POST['gallery'];
instead of this:
$gallery = array($_POST['gallery']);
You passing an array that you did not index properly
Or you can try it this way:
$gallery = array('gallery' => $_POST ['gallery']);
or
$image = $sitemap->gallery[$gallery[0]]->addChild('image');
either way should fix the problem

thank you very much, but I tested this and is giving me the same error
$gallery=array('gallery'=>$_POST['galeria']);
$image = $sitemap->gallery[$gallery]->addChild('image');
I do not understand the select form that I have is as follows:
<select id="textfield" name="galeria">
<option id="textfield" value="">Escoger de la Lista</option>
<?php
$source = 'content.xml';
// load as string
$xmlstr = file_get_contents($source);
$sitemap = new SimpleXMLElement($xmlstr);
// load as file
$sitemap = new SimpleXMLElement($source,null,true);
//$bar_count = $sitemap->gallery->count();
//for($i=0;$i<$bar_count;$i++){
$contador="0";
foreach($sitemap->gallery as $content) {
$atributo = $content->attributes();
echo "<option id='textfield' value='".$contador."'>".$atributo['Name']. "</option>";
//}
$contador++;
}
?>
</select>
anyway I've tried has done an echo and I get the result, do not really understand

Related

getting error in assign array value to variable in php

I have following function to fetched value from db:
$src = getSrc($r['Section']);
I want to return 2 variables value from function. So, I have stored it in array,as follow:
$src['img'] = $row['img'];
$src['link'] = $r2['link'];
print_r($src);
return $src;
Output for print_r($src); is:
Array ( [img] => images/about_us.jpg [link] => About Us )
But when I assigned this value to variable as follow:
$src_val = $src['img']."<br>";
$link_val = $src['link'];
It gives output as
images/about_us.jpg
i
I am not able to get value of $link_val. Please explain.
I don't know how did you get that print_r output from, but this
$src = $row['img'].";". $r2 ['link'];
should be
$src = array('img' => $row['img'], 'link' => $r2['link']);
Update
Typo in $src['link'] = $r2['link'];?
Should be
$src['link'] = $row['link'];

php JSON_DECODE for different data length

From mysql, I have a data BLOB data type which has two different scenarios (Please see below). I am trying to put them into a string. Below is the process that I am doing:
1. Query:
$names= $results[0]->name;
print_r($names);
First scenario:
[{"Name":"Mike"},{"Name":"Sean"}]
Second scenario:
{"Name":"Mike Smith","Spaces":"1"}
2. JSON_DECODE
$data = json_decode(stripslashes($names),true);
print_r($data);
First scenario:
Array
(
[0] => Array
(
[Name] => Mike
)
[1] => Array
(
[Name] => Smith
)
)
Second scenario:
Array
(
[Name] => Mike Smith
[Spaces] => 1
)
3. What I am trying to do: To put them into a string
$string = '';
for ($i=0; $i <sizeof($data) ; $i++){
$row = $data[$i];
$name = $row -> Name;
if(isset($row -> Spaces)){
$number = '(' . $row -> Spaces . ')';
}else{
$number = '';
};
$string .= $name . $number . ', ';
};
//Remove last comma
$refined = rtrim($string,', ');
print_r($refined);
4. ISSUE
The issue I am having is that because the data can have two different scenarios like shown in the "1.Query", I can't predict or generalize it and getting errors like "Trying to get property of non-object".
How can I fix this?
Since you're passing true to the $assoc parameter of json_decode, $row->Name will never be the right syntax, since you have an array, and that's syntax for accessing objects; you want $row['Name'] instead. (It's unusual to put space around the -> by the way.)
However, you have basically the right idea on this line:
if(isset($row -> Spaces)){
For an array, that would instead by:
if(isset($row['Spaces'])){
You can do the same thing to see if you've got a name, or a list of names:
if(isset($row['Name'])) {
// In scenario B
echo $row['Name'];
// check for 'Spaces' etc
} else {
// In scenario A
foreach ( $row as $item ) {
echo $item['Name'];
}
}
Note my use of a foreach loop here, which is much neater than your for loop for this kind of thing.
Well I'll edit my answer for better understanding
$str1 = '[{"Name":"Mike"},{"Name":"Sean"}]';
$str2 = '{"Name":"Mike Smith","Spaces":"1"}';
$json1 = json_decode($str1, false);
$json2 = json_decode($str2, false);
if(is_object($json1))
{ echo 'json1 is object<br>'; } else
{ echo 'json1 is NOT object<br>'; }
if(is_object($json2))
{ echo 'json2 is object'; } else
{ echo 'json2 is NOT object'; }
http://php.net/manual/en/function.is-object.php

PHP How to print a single value from this Array?

I have an Array like this one:
Array ( [0] => a:39:{s:2:"id";s:6:"703981";s:4:"name";s:10:"Bilton Apt";s:7:"address";s:25:"Hart Blvd, Paradise Acres";s:3:"zip";s:2:"PO";s:10:"city_hotel";s:11:"Montego ....etc...
And i want to print in the page the "name" value so i wrote these two lines of code:
$item = get_post_meta($post->ID, '_ihfc_hotel');
echo $item['name'];
But when i load the page i receive this error:
Notice: Undefined index: name in /Applications/MAMP/htdocs/wp_test_csv/wp-content/themes/twenty....etc
i tried with other solutions like:
echo $item[0]['name']; or echo $item[0]->['name']:
But none works
Some one can help me?
You need to unserialize the array, as told in the comments:
$ar = unserialize($item[0]);
echo $ar['name'];
You can put it in a loop to get all values in a multi dimensional array:
foreach($item as $key=>$value){
$ar[$key] = unserialize($value);
}
and then access it:
echo $ar[0]['name'];
As Jon Stirling and u_mulder said, your array contains a serialized value and the only one shown in your example is index 0.
So due the fact that your example string is cut short with ....etc... I can only answer to what is known.
$data = unserialize($item[0]);
print_r($data);
echo $data['name'] // Bilton Apt
This should do that trick.
Did you mean:
<?php
$name = get_post_meta($post->ID, '_ihfc_hotel', true);
echo $name;
Otherwise
<?php
$data = get_post_meta($post->ID, '_ihfc_hotel', true);
$data = unserialize($data);
var_dump($data);
var_dump($data['name']);

Access php array index issue

After use fgetcsv() function I get an array, then I use a foreach() and I get a "simple" associative array like:
Array
(
[ix,radical,variant,simplified,pinyin,english,strokes] => 1,一,,,yi1,one,1
)
Then I try to access any element and I fail:
echo $record['ix'];
Notice: Undefined index: ix
echo next($record); // return nothing!
Maybe is offtopic (not centred in php language) but I'm using some lib (not necessary of course from PHP commenter in http://php.net/manual/es/function.fgetcsv.php)
<?php
require "..\CsvImporter.lib.php";
$importer = new CsvImporter('my_route\\my.csv',true);
while($records = $importer->get())
{
// debug
print_r($records[0]);
exit;
foreach ($records as $record)
{
\\ ..
}
}
And my screen output is
Array ( [ix,radical,variant,simplified,pinyin,english,strokes] => 1,一,,,yi1,one,1 )
My data:
ix,radical,variant,simplified,pinyin,english,strokes
1,一,,,yi1,one,1
2,丨,,,gun3,line,1
3,丶,,,zhu3,dot,1
So how is possible I'm unable to access any key ?
As you posted your data above. Your csv importer giving you each row with comma. So you need to explode it then use however you want to use
Example code \
$i=0;
while($records = $importer->get())
{
if($i>0) //skip first row it is heading
{
$data = explode(',',$records);
print_r($data);
// now `$data[0]` contains `ix` value for your first csv row and so on
}
$i++;
}
I used some lib and the default delimiter was "\t" so something like 'ix,radical,variant,simplified,pinyin,english,strokes' was THE key and '一,,,yi1,one,1' the only value
Now, I see the problem I can do it easy:
$f = 'file.csv';
$separator = ',';
$file = file_get_contents($f);
// bi-dimensional array
$regs = array_map(function($reg){return (explode($separator,$reg));},explode("\n",$file));
Thanks all!

Printing contents of a nested array

I am trying to print the contents of a nested array, but it simply returns "Array" as a string yet will not iterate with a foreach loop. The arrays are coming from a mongodb find(). The dataset looks like this:
User
Post_Title
Post_Content[content1,content2,content3]
I am trying to get at the content1,2,3.
My current code looks like this:
$results = $collection->find($query);
foreach ($results as $doc)
{
echo $doc['title']; //this works
$content[] = $doc['content'];
print_r($content); //this prints "Array ( [0] => Array )"
foreach ($content as $item)
{
echo $item;
}
}
All this code does is print the Title, followed by Array ( [0] => Array ), followed by Array.
I feel quite stupid to not figure out something that seems so basic. Most posts on stack overflow refer to multidimensional associative arrays - in this case, the top level array is associative, but the content array is indexed.
I have also tried
foreach ($doc['content'] as $item)
But that gives
Warning: Invalid argument supplied for foreach()
I even tried iterating over the returned array again using a nested foreach, like the following:
foreach ($results as $doc)
{
echo $doc['title']; //this works
$content[] = $doc['content'];
print_r($content); //this prints "Array ( [0] => Array )"
foreach ($content as $item)
{
foreach ($item as $next_item)
{
echo $next_item;
}
echo $item;
}
}
The second foreach failed with an invalid argument..
Any thoughts would be greatly appreciated.
edit: perhaps it has something to do with how I am inserting the data to the DB. That code looks like this
$title = $_POST['list_title'];
$content[] = $_POST['list_content1'];
$content[] = $_POST['list_content2'];
$content[] = $_POST['list_content3'];
$object = new Creation();
$object->owner = "$username";
$object->title = "$title";
$object->content = "$content";
$object->insert();
Is this not the proper way to add an array as a property to a class?
The issue is some of array content is an array while other parts are strings. You should test for the sub content $doc being an array using is_array(). If it is, loop through the $doc like you would any other array, and if it isn't, you can echo the content (may need to test the content type before doing this if you're uncertain as to what content it can be)
The problem is in the code that you are saving data. You should replace the following line
$object->content = "$content";
with
$object->content = $content;

Categories