I have an item object in PHP, which has the following structure on var_dump :
$item->properties:
array (size=1)
1 =>
array (size=4)
'Key1' => string 'Value1' (length=6)
'Key2' => int 1
'Key3' => string 'true' (length=4)
'Key4' => string 'true' (length=4)
I want to access Key, value in a foreach loop and assign Key, value pair to some internal variables, however when i am using the foloowing code to loop pver array of array, i am getting error in accessing the values in the way i want. Here is what i am doing :
foreach($item->properties as $property) {
foreach($property as $value) {
echo $value;
}
}
Anyone have an idea what am i doing wrong, and how can i fix that ?
one of the things you provide to the foreach isn't a a valid argument, as the error says. Find out which of the 2 it is (linenumber) and var_dump that argument to see what type it is (probably "not an array" ).
In the end either $item->properties itself, or the array values of that array (if it is one), so $property is not an array.
It could be, for instance, that maybe the first key of the properties IS an array, but the second isn't? then you could use is_array to check.
Related
I have a URL in this format:
https://www.example.com/page?=item1&item2&item3&item4&item5
I need to put each item into a variable, likes this:
$var1 = item1;
$var2 = item2;
$var3 = item3;
$var4 = item4;
$var5 = item5;
It does not actually say item1, item2 etc in the URL, their actual values are different every time.
Does anyone know how to do this?
Thanks!
The URL Query String / GET-Parameters
Your example URL https://www.example.com/page?=item1&item2&item3&item4&item5 is malformed. The query string starting after the question mark ? is parsed with the format:
name1=value1&name2=value2...
Your URL means:
<empty name> = item1
item2 = ''
item3 = ''
...
Empty names are ignored when PHP parses GET-parameters.
Let's assume you have an URL https://www.example.com/page?item1&item2&item3&item4&item5 instead. (Note the remove =.)
Accessing GET-Parameters
If the given URL is the one of you PHP current script, you can easily access the GET-parameter using the preinitialized global variable $_GET. Try var_dump($_GET) and you get:
array (size=5)
'item1' => string '' (length=0)
'item2' => string '' (length=0)
'item3' => string '' (length=0)
'item4' => string '' (length=0)
'item5' => string '' (length=0)
As you can see, item1...item5 are the keys of the associative array, each with an empty string '' as the default value since you did not set any by item1=the+item.
Get The Keys as Array
To get closer to your needs specified in the title of your question, you can extract the keys using array_keys:
$url_keys = array_keys($_GET);
Now you have an array like this:
array (size=5)
0 => string 'item1' (length=5)
1 => string 'item2' (length=5)
2 => string 'item3' (length=5)
3 => string 'item4' (length=5)
4 => string 'item5' (length=5)
Extracting as Variables
I do not recommend to extract any changing data structures into your variable scope. Be aware that the client could even manipulate the request sending you something you do not expect. It is hard to find variable names when you do not exactly know what you get. Prefer to operate on arrays.
However, if you really need to import the keys into your variables scope, here are the ways how you can achieve that. PHP does provide a function extract that can do that in several ways. We want to use the numeric indexes with a prefix to become the variable names:
extract(array_keys($_GET), EXTR_PREFIX_ALL, 'var');
The result will be:
$var_0 = item1,
$var_1 = item2
The zero-based numbering is due to the fact, that arrays are nubered zero-based by default, so the returned array from the function array_keys.
To get the numbering as illustrated in your question, you can also renumber the array of keys.
extract(array_combine(range(1, count($_GET)),array_keys($_GET)), EXTR_PREFIX_ALL, 'var');
If you are bothered by the underscore within the names, you can also extract the keys using dynamic variable creation in a fairly simple loop:
foreach (array_keys($_GET) as $k => $v)
${'var'. ($k+1)} = $v;
When you want global variables instead, use
foreach (array_keys($_GET) as $k => $v)
$GLOBALS['var'. ($k+1)] = $v;
Extract Keys from Arbitrary URL
If you have to analyze a URL string from somewhere, you can use the parse_url function to extract the query first and then use parse_str which parses a query in the same way as PHP does automatically with the script's URL when building the $_GET associative array on startup.
parse_str(parse_url($url, PHP_URL_QUERY), $params);
$params is now
array (size=5)
'item1' => string '' (length=0)
'item2' => string '' (length=0)
'item3' => string '' (length=0)
'item4' => string '' (length=0)
'item5' => string '' (length=0)
You can handle that in the same way as shown above with the $_GET array.
You could try this
$var1 = $_GET['item1'];
$var2 = $_GET['item2'];
$var3 = $_GET['item3'];
$var4 = $_GET['item4'];
$var5 = $_GET['item5'];
All your URL variables are stored in the GET array
I am not sure about your URL format...
However, as already answered here, you can extract each parameter (if specified by name) using $_GET['item1'] etc...
And, if there some other format or Unknown number of values, you can work over the whole URL by getting it using $_SERVER['REQUEST_URI'] which will give the string:
/page?=item1&item2&item3&item4&item5
then, splitting that string with seperator &, assuming every splitted substring is a value of an item in the array (?) in the URL.
As you say, you want to get all parameters in your URL.
Actually, $_GET is already an array that you also can use. But when you want to create your own array / variable list, that is also possible.
To do that, you can use the super global $_GET, this is an array with every URL parameter in it.
For example, I made this code for you
<?php
$return = [];
foreach($_GET as $key => $value) {
$return[$key] = $value;
}
var_dump($_GET);
var_dump($return);
?>
When I visit the page (http://example.com/temp.php?a&b), it will result in
array(2) { ["a"]=> string(0) "" ["b"]=> string(0) "" } array(2) { ["a"]=> string(0) "" ["b"]=> string(0) "" }
As you can see, this has the same data. And, because you say that the values and maybe also the keys (file.php?key=value) can be diffrent, I recommend you to use the array.
So, you can also save them in formats like JSON, to easilly save the in the database, so you can use the afterwards.
When I use json_encode on one of the arrays it gives me a string that you can use.
{"a":"","b":""}
With json_decode you can change it back to the array
I work with a CMS (Drupal 8). It automatically generates some multidimensional array with an unique value, like this :
//var_dump of my $array
array (size=1)
0 =>
array (size=1)
'value' => string '50' (length=2)
To date, I use this ugly way for automatically get the value (in example : "50") of these arrays :
array_shift(array_values(array_shift(array_values($array))))
My question is, is there a better way in php for get that ?
So you know it's an array in an array?
$value = reset(reset($array));
You don't know how many turtles arrays are nested?
$value = $array;
while(is_array($value))
$value = reset($array);
Docs on reset
Just use via index:
$array[0]['value']
I have an object that needs to be returned, however I need to perform some pre-return manipulation before returning it.
The object has the following format:
object(PaginationHelper)[3]
public 'current_page' => int 1
public 'items_per_page' => int 10
public 'dataset' =>
array (size=10)
0 =>
object(AdvertSet)[4]
public 'Keywords' => string '' (length=0)
protected 'Adverts' =>
array (size=3) // SIZE = 3 SO REMOVE THIS FROM 'dataset' ARRAY
...
public 'LiveStatus' => boolean false
1 =>
object(AdvertSet)[5]
public 'Keywords' => string '' (length=0)
protected 'Adverts' =>
array (size=1) // SIZE = 1 SO KEEP THIS IN 'dataset' ARRAY
...
public 'LiveStatus' => boolean false
etc etc ....
[End Object]
What I need to do:
Remove all parts of the 'dataset' array that doesn't have an 'Adverts' count of 1, thereby preserving only those datasets that have an 'Adverts' array size of 1.
Retain the fact that it is an object, to be returned.
I've tried multi-dimensional recursive functions to get through this, however the fact that it's an object and not an array is making progress hard, and I'm not sure I would be able to convert from an object to an array and back again without messing up the object's internals.
Can anyone help with this? Here's what I've gotten so far with a foreach...
foreach($results as $key => $value) {
if($key == 'dataset') {
// value is right array to check count
foreach($value as $k => $v) {
echo $v;
}
}
}
It doesn't work, but that's the method I'm currently working on.
I've also tried something like:
if(count($results->dataset->(Array)AdvertSet->Adverts == 1) { }
but I can't cast AdvertSet as Array.. Any help would be greatly appreciated!
Just a quick note: it doesn't have to be removed from the array, I just eventually need the same object without those that have an Adverts count of 3. So this could involve copying to a new array without those that have an Adverts count of <> 1.
My first thought was:
foreach($PaginationHelper->dataset as &$data) {
if(count($data) !== 1)
unset($data);
}
But after reading your question for the third time, I see you want to remove only those elements with a Adverts count not equal to 1.
Looking at your structure, the Adverts array is protected, and therefore there is now way to access it without subclassing Advertset object.
So, my final answer must be: It is not possible to remove them, with this structure!
Your data structure is not really recursive and you don't need recursive traversal.
You only need to iterate over the $object->dataset array and delete items where the count of adverts is not 1. Since you're trying to filter items over a protected property, one approach would be to implement a AdvertSet::count() method that would return number of contained adverts: $object->dataset[$i]->Adverts->count() != 1. I would advise against forcing your way to access the protected property just for the filtering's sake.
I have an array that outputs like this:
1 =>
array
'quantity' => string '2' (length=1)
'total' => string '187.90' (length=6)
2 =>
array
'quantity' => string '2' (length=1)
'total' => string '2,349.90' (length=8)
I would like to loop through each array keys and retrieve the set of 3 values relating to them, something like this (which doesnt work):
foreach( $orderItems as $obj=>$quantity=>$total)
{
echo $obj;
echo $quantity;
echo $total;
}
Would someone be able to give some advice on how I would accomplish this, or even a better way for me to be going about this task. Any information relating to this, including links to tutorials that may cover this, would be greatly appreciated. Thanks!!
foreach( $orderItems as $key => $obj)
{
echo $key;
echo $obj['quantity'];
echo $obj['total'];
}
Using the above.
You need to read the docs on forEach() a little more, since your syntax and understanding of it is somewhat incorrect.
$arr = array(
array('foo' => 'bar', 'foo2', 'bar2'),
array('foo' => 'bar', 'foo2', 'bar2'),
);
foreach($arr as $sub_array) {
echo $sub_array['foo'];
echo $sub_array['bar'];
}
forEach() iteratively passes each key of the array to a variable - in the above case, $sub_array (a suitable name, since your array contains sub-arrays). So within the loop body, it's that you need to interrogate.
I'm total newbie to PHP and Drupal but I fix this simple(?) thingo on my template. I want to get title, date, text and link path from this array? I can't get it out of there. I think its because its in inside of another array and because im noob in PHP I cant get it out of there ? Also I would like to get it to a loop. If theres more content, I would get it as a list or something. I would use foreach for this? Like foreach $contents as $content and so on?
I get this output from this: var_dump($contents);
array
'total' => string '1' (length=1)
'data' =>
array
0 =>
array
'cid' => string '13231' (length=3)
'title' => string 'TITLEBLABLABLA' (length=3)
'body_text' => string 'TEXTBLABLABAL' (length=709)
'created' => string '313131' (length=10)
'created' => string '2010-07-13 14:12:11' (length=19)
'path' => string 'http://goog.fi' (length=72)
Think of accessing multidimensional arrays in the same way you'd access a file in a subdirectory: just reference each level/directory in sequence. Assuming that array is stored in $arr, you'd get the title as follows:
$arr['data']['0']['title']
Here is a basic PHP array tutorial
It comes down to this:
You retrieve an element of an array with []
$array = array( 'a' => 'b');
echo $array['a']; //Prints b;
To loop through a multi-dimensional array and echo date try this...
foreach ($contents as $key => $content) {
echo $content[$key]['created'];
}
If that doesn't work, post the output of print_r($content) in your question so I can't build you exact array. I'm kinda confused over the structure of your array in your question.