<?php
$json_string = file_get_contents('infile.json');
$get_json_values=json_decode($json_string,true);
foreach ($get_json_values as $key=>$getlikes) {
if($getlikes[$key]['type']=='like') {
?>
<div><p><?php echo $getlikes['name'] ?></p></div>
<?php
}}
?>
There is an error in the code above: undefined offset on the line with the if. I guess it is because $getlikes[$key]['type'] is wrong. What would be the proper code to get all the objects with the type attribute being "like"?
Json can be downloaded from here
This really depends on the content of your .json object. But most likely the undefined offset is being caused because not all $getlikes[$key] has an array key of 'type'. Validate to make sure it exists before you compare. Try
foreach ($get_json_values as $key=>$getlikes) {
if(!isset($getlikes['type'])) continue;
if($getlikes['type']=='like') {
....
EDIT:
Based on your .json file you were just adding an additional key which was unneeded. Changed the code to reflect the correct call. Still not a bad idea to check if a value is set. Try a var_dump($getlikes) or on the file you are using to get a good look at what you are iterating over.
Given the JSON string it's clear what you're doing wrong. $get_json_values is a list with no indexes, you're doubling up on the key, hard to explain. Do this instead.
foreach ($get_json_values as $getlikes) {
if($getlikes['type']=='like') {
If you were to use $key, you'd use it like this
foreach ($get_json_values as $key=>$getlikes) {
if($get_json_values[$key]['type']=='like') {
but you wouldn't do that anyway. Foreach extracts the elements one by one.
Related
I think the best way to explain my question is to give an example. Say I have the following object.
$data=new stdClass;
$data->test=new stdClass;
$data->test->test2=6;
$data->s=array('b',6,7);
I want to know how I can read or change any value in the object given the key value as an array.
I know the below won't work:
function doSomething($inputArray1,$inputArray2) {
$data[ $inputArray1 ]; //6
$data[ $inputArray2 ]=4; //was array('b',6,7);
}
//someone else provided
doSomething( array('test','test2') , array('s') );
Changed to make clear that I do not know the values of the array personally so using
$data->test->test2; to get the 6 like I normally would won't work. Also do not know the array length.
Figured it out:
$parts=array('test','test2');
$ref=&$data;
foreach($parts as $part) {
if (is_array($ref)) {
$ref=&$ref[$part]; //refrence next level if array
} else {
$ref=&$ref->$part; //refrence next level if object
}
}
echo $ref; //show value refrenced by array
$ref=4; //change value refrenced by array(surprised this works instead of making $ref=4 and breaking the refrence)
unset($ref); //get rid of refrence to prevent accidental setting. Thanks #mpyw
As I noted in the comments, you need to access the object/arrays as intended.
Their notations are as follows;
Object: ->
Array: []
So, taking your $data array you've generated, you'd have to access the object/array combination as such:
echo $data->s[2];
Example/Demo
And if you were to access the initial test/test2 itteration (which is set as an object (->)), then you need to access it as an object:
echo $data->test->test2;
I just started learning PHP and I am having some difficulties with some of the coding.
Hopefully, someone could help me a little.
I'm using this:
if(!empty($_POST['yyy'])) {
foreach($_POST['yyy'] as $a1) {
echo " $a1";}}
The echo will write several results of $a1 depending on how many were selected in the form.
What I want is to save those results to some values so I can add them in MySQL.
Something like this:
if(!empty($_POST['yyy']))
{
foreach($_POST['yyy'] as $a1)
{
echo " $a1"; where $a1 will create a $result1,$result2,$result3(for each isset)
}
}
Then if I use:
echo "$result2";
it will give me the second result.
Not clear whether you are asking about this kind of result or not. But you can use an array to store each values inside the foreach loop.
var data=[];// define an array to access outside of if statement later..
if(!empty($_POST['yyy'])) {
foreach($_POST['yyy'] as $a1){
data[]=$a1;
//or can use array_push() method
array_push(data,$a1);
}
}
/*this will give the second result(because array indexing starts from 0. So to get third result
use data[2])*/
echo data[1];
Furthermore by echoing quoted variable will not give the value of that variable but gives a string literal.
echo "$result2" //output---> $result
I've been trying for a while. I have tried several things to fix this, but I just can't get it to work.
My code:
<?php
if (is_array($row))
{
foreach ($row as $data) {
echo array_unique($data->username);
}
}
?>
It gives me the following error
Message: array_unique() expects parameter 1 to be array, string given
I have no idea what is going on with this. I have even tried placing the array_unique in the $row.
So like:
<?php
if (is_array($row))
{
foreach (array_unique($row) as $data) {
echo $data->username;
}
}
?>
But this gives me another error:
Object of class stdClass could not be converted to string
I have no idea what's going on. I have searched for hours but haven't found anything on here. Any help is greatly appreciated. Thanks.
You can't use array_unique on multi-dimensional arrays when you're looking inside the depth. Its works on flat one, and certainly won't work on strings. An alternative is to create another container for that and use usernames as keys, then you'll get unique ones.
Since you haven't shown the array/object structure, here a little bit on an idea on the comment I gave above:
$container = array();
foreach($row as $data) {
if(!isset($container[$data->username])) {
$container[$data->username] = $data;
}
}
// $container = array_values($container); // optional simple reindex
foreach loop only repeating the last element of the arary?
java Script Code :
<?php foreach($_REQUEST["itemprice"] as $itemprice)
{
?>
+ "&itemname_price[]=<?php echo $itemname?>_price=" + <?=$itemname?>_price.value
<?php
}
?>
Code to request that data
$items_price = array();
foreach($_REQUEST['itemname_price'] as $itemname_pric) {
$items_price[]=$itemname_pric;
}
print_r($items_price);
foreach is used to get the values from an array, and what you are trying here is to get data from a specific array key. I guess that's why you are getting a single value. You can refer to
http://php.net/manual/en/control-structures.foreach.php to get the exact use of foreach.
Let me know if you have anything to know.
I'm trying to pass 3 parameter to a script, where the 3rd parameter $_GET['value3'] is supposed to be an array
$_GET['value1']
$_GET['value2']
$_GET['value3'] //an array of items
I'm calling the script like this: (notice my syntax for value3, I'm not sure it's correct)
http://localhost/test.php?value1=test1&value2=test2&value3=[the, array, values]
I then use a foreach to hopefully loop through the third parameter value3 which is the array
//process the first input $_GET['value1']
//process the second input $_GET['value2']
//process the third input $_GET['value3'] which is the array
foreach($_GET['value3'] as $arrayitem){
echo $arrayitem;
}
but I get the error Invalid argument supplied for foreach()
I'm not sure if my methodology is correct. Can some clarify how you'd go about doing the sort of thing
There is no such thing as "passing an array as a URL parameter" (or a form value, for that matter, because this is the same thing). These are strings, and anything that happens to them beyond that is magic that has been built into your application server, and therefore it is non-portable.
PHP happens to support the &value3[]=the&value3[]=array&value3[]=values notation to automagically create $_GET['value3'] as an array for you, but this is special to PHP and does not necessarily work elsewhere.
You can also be straight-forward and go for a cleaner URL, like this: value3=the,array,values, and then use explode(',', $_GET['value3']) in your PHP script to create an array. Of course this implies that your separator char cannot be part of the value.
To unambiguously transport structured data over HTTP, use a format that has been made for the purpose (namely: JSON) and then use json_decode() on the PHP side.
try
http://localhost/test.php?value1=test1&value2=test2&value3[]=the&value3[]=array&value3[]=values
For arrays you need to pass the query parameters as
value3[]=abc&value3[]=pqr&value3[]=xyz
You can cast the name of the index in the string too
?value1[a]=test1a&value1[b]=test1b&value2[c][]=test3a&value2[c][]=test3b
would be
$_GET['value1']['a'] = test1a
$_GET['value1']['b'] = test1b
$_GET['value2']['c'] = array( 'test3a', 'test3b' );
http://php.net/manual/en/reserved.variables.get.php
Check out the above link..
You will see how the GET method is implemented.
What happens is that the URL is taken, it is delimited using '&' and then they are added as a key-value pair.
public function fixGet($args) {
if(count($_GET) > 0) {
if(!empty($args)) {
$lastkey = "";
$pairs = explode("&",$args);
foreach($pairs as $pair) {
if(strpos($pair,":") !== false) {
list($key,$value) = explode(":",$pair);
unset($_GET[$key]);
$lastkey = "&$key$value";
} elseif(strpos($pair,"=") === false)
unset($_GET[$pair]);
else {
list($key, $value) = explode("=",$pair);
$_GET[$key] = $value;
}
}
}
return "?".((count($_GET) > 0)?http_build_query($_GET).$lastkey:"");
}
Since, they are added as a key-value pair you can't pass array's in the GET method...
The following would also work:
http://localhost/test.php?value3[]=the&value3[]=array&value3[]=values
A more advanced approach would be to serialize the PHP array and print it in your link:
http://localhost/test.php?value3=a:3:{i:0;s:3:"the";i:1;s:5:"array";i:2;s:6:"values";}
would, essentially, also work.