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']);
Related
Im new at this and not sure how to fill an array and echo it. Can someone please help me? :)
First my array, that I hope is retrieving info from my notes.txt-file, if there is any?! Im not sure if i need both declarations?:
$test = array();
$test[] = json_decode(file_get_contents($file), TRUE);
Anyway, this is the code for adding elements to the array, the input from the user:
$name = guestbook_input($_POST['name']);
$comment = guestbook_input($_POST['comment']);
$test[] = [
'name' => $name,
'comment' => $comment,
'ip' => $_SERVER['REMOTE_ADDR'],
'time' => date("y-m-d H:m")
];
// Write input to file
file_put_contents($file, json_encode($test));
This code works fine (I think) and writes to the file.
Finally Im trying to echo the array to a table like this:
<?php
$getfile = json_decode(file_get_contents('./notes.txt'), TRUE);
foreach ($getfile as $value): ?>
<tr>
<?php
echo '<td>';
echo $value['name'];
echo '</td>';
echo '<td>';
echo $value['comment'];
echo '</td>';
echo '<td>IP:';
echo $value['ip'];
echo "<br>Tid:";
echo $value['time'];
echo '</td>'?>
</tr> <?php endforeach; ?>
This code do print elements, but only for the first input in my guestbook. I have no idea if this is the right way to do this or not, but hopefully someone can help me with this, so I can get this right?!
First, your declaration and assignment:
$test = array();
$test[] = json_decode(file_get_contents($file), TRUE);
The function json_decode(), as you're calling it, returns an array, so it is not necessary to declare the variable first, but it is good practice to do so. However, in the function call, you are actually assigning the entire results to $test[0], since $test[] simply creates a new element with the next numeric index. The code where you assign the user input is correct, so it gets output correctly.
You are putting your array that you read from a file into a single element of the array $test.
Then you are adding your new entry as the second element.
You should initialise the array as:
$test = json_decode(file_get_contents($file), TRUE);
I have a PHP session array where it can be counted as multidimensional array, basically I am trying to store data inside my session array and i am successfully obtaining that part of the task. The main issue is, I am not able to echo them specifically and I have to use var_dump. When I try to print them with echo i got an notice which says array to string conversion. Please any help I would be appreciated how to print them with their own specific keys or values. The code as follows:
if (!is_array($_SESSION['products']['names'])){
$_SESSION['products']['names'] = array();
$_SESSION['products']['names']['prices']= array();
}else {
$pros = $_SESSION['products']['names'];
if (in_array($product->getName(), $pros, true)){
echo 'The product is available in your basket';
} else {
array_push($_SESSION['products']['names'],$product->getName());
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
foreach ($_SESSION['products'] as $val){
echo $val['names'];
echo $val['prices'];
}
}
}
The output that I receive as follows:
Notice: Undefined index: names in
Array to string conversion in
Use join() function in your foreach, like this:
echo join('<br>', $val);
Or instead of
echo $val['prices'];
write
echo $val['names']['prices'];
This is your problem...
// Here your assigning `['names']` as a string..
array_push($_SESSION['products']['names'],$product->getName());
// Then here you're overwriting the string with an array...
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
Change the first one to this..
array_push($_SESSION['products']['names']['name'],$product->getName());
Assuming $product->getPrice() returns a string or a number...
foreach ($_SESSION['products'] as $val){
foreach($val['names'] as $name){
echo $name['name'];
echo $name['prices'];
}
}
There is no issue with the code you have here. I don't see you trying to echo or vardump them directly so please show the code you are echoing them out specifically or the output from above and which line is giving you an issue.
If you want to echo each one out with it's price.
for($i=0;$i<count($_SESSION['products']['names']);$i++) {
echo $_SESSION['products']['names'][$i] . " " . $_SESSION['products']['names']['price'][$i];
}
I am having a problem with getting data from json. I cant change the way it is saved in the database since it is generated by the framework and after that read for the fields generation. My json looks like this:
{"102":{"textinput":{"comment":"2"}},"104":"34"}
OR
{"78":{"textinput":{"comment":"1"}},"82":"34"}
Comment value is my serialnumber that I net to get from this json. I tried with :
$json_sn = json_decode($customer_json_sn, true);
$snr = $json_sn['78']['textinput']['comment'];
But this is not the solution I need, since I never know the value of first numeric key, I cant rely on that. Any help would be appreciated.
If this format is going to be always the same, you can use reset() function on this one. Consider this example:
$json_sn = json_decode($customer_json_sn, true);
$snr = reset($json_sn);
echo $snr['textinput']['comment'];
How about:
$snr_array = array()
foreach ($json_sn as $key)
snr_array[] = $key['textinput']['comment'];
Edit: I just realized that you might just need/get one comment:
$key = key($json_sn);
$snr = $json_sn[$key]['textinput']['comment'];
You can do:
<?php
$json = '{"78":{"textinput":{"comment":"1"}},"82":"34"}';
var_dump(json_decode($json, true));
$data = json_decode($json, true);
foreach( $data as $key => $value ) {
# Check if exsit
if (isset($value['textinput']['comment'])) {
echo "Value: " . $value['textinput']['comment'];
}
}
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;
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