Here's a representation of my array:
$arr
[0]
[code]='a code'
[number]='a number'
[1]
[code]='a code'
[number]='a number'
[2]
[code]='a code'
[number]='a number'
[3]
.
.
I'm doing a foreach loop to get all the [code] values am stuck: I forgot how to do it. Can anyone please help me with it?
You can just cast the array as an object of type stdClass
$obj = (object) $arr
That said however, your post title seems to imply you want an object, but the post body seems like you just want to access an array key.
In which case you can just use the following. But it depends what exactly you mean by 'get all of the [code] values.'
foreach( $arr as $inner_array ) {
$codes[] = $inner_array['code']; // Collect them all into a single dimensional array?
echo $inner_array['code']; // Output it here?
}
Maybe something like :
foreach($arr as $item) {
echo 'code: ' . $item['code'];
}
I hope it will help !
foreach($arr as $item) {
echo 'code:'.$item['code'];
}
I hope this helps.
Related
this might be very simple, and well, yes ... I may not fully understand how objects work, which seems to be the real problem here. So thanks for helping! ^^
I've got an Object that kinda looks like this.
$myobject = Array( [some_random_name] => "Value to that random name" )
Since I'm not sure how those two bits of information are called (sry for that) I will refer to them as "name" and "value". My question is: how do I extract these informations? I need both, the "name" and the "value", so I can store them in two variables ($namevar, $nameval), which should then output something like this:
echo($namevar) = "some_random_name"
echo($nameval) = "Value to that random name"
Thanks.
well, you are using an Array, not an object. in order to get the array keys or values, you could use the following functions: array_values & array_keys.
i could add code snippets etc, but its really straight forward in php's docs:
http://php.net/manual/en/function.array-values.php
http://php.net/manual/en/function.array-keys.php
you could also possibly iterate the array or object (works the same for both), using something like the following code:
foreach($object as $key => $value) { ... }
you can use :
$myobject = [ 'key' => 'value' ];
$key = key($myobject);
$value = $myobject[$key];
echo $key; // key
echo $value; // value
it will return the key value for the current array element
see documentation
or you can use a foreach loop like this:
foreach($myobject as $key => $value) {
$namevar = $key;
$nameval = $value;
}
Basically you are asking how do we get the value of array objects? how do we use them?
These are array objects.
echo $yourObjectname->yourpropertyname;
in your case
echo $myobject->some_random_name;
Example -
$arr = Array (
[0] => stdClass Object (
[name] => 'abc'
);
echo $arr[0]->name;
Object is an instance of class or we can say an medium to use classes properties variable and methods.
I want to find a way to drill down into the $_FILES array and retrieve the [type] => Array in its entirety. I have tried a number of approaches can't get anywhere with this:
$result = preg_grep('/\image\b/', $_FILES);
When I output $result in this manner:
echo '<pre>';
print_r($result);
echo '</pre>';
I get the following:
Array (
)
Which is of course useless. I've been going through the Manual, looking at all the array functions, but haven't found anything that works. Is there a PHP function for this? Any help would be very much appreciated!
Cheers,
shackleton
PS I've also tried to use:
foreach ($_FILES['userfile']['type'] as $key => $value) {
to create my own array with both the key and value of each file uploaded. The problem with that is the variable will not create an array with more than one - [0] - index because the array construct is referencing the variable. That seems to be a dead end.
If you're sending multiple files, you should iterate using $_FILES only, as this:
$types=array();
foreach($_FILES as $filename=>$arrayofvalues){
$types[]=$arrayofvalues['type'];
}
Holla Ricardo,
Thanks so much, that works like a charm. I had to go find a way to flatten the resulting array, but did find a function online that works. I had been looking for that function too for several days. Here's what I came up with:
// Create an array of only the file type
$types = array();
foreach ($_FILES as $filename => $arrayofvalues) {
$types[] = $arrayofvalues['type'];
}
// Create a sub-array of types
foreach($types as $subArray) {
foreach($subArray as $val){
$simple[] = $val;
}
}
echo "Simple images array:";
echo '<pre>';
print_r($simple);
echo '</pre>';
"<br />";
// Get the key & value of just image files
$images = preg_grep('/\image\b/', $simple);
// Use the differenc array function to find the indices I want
$dif = array_diff($simple, $images);
echo "Difference:";
echo '<pre>';
print_r($dif);
echo '</pre>';
"<br />";
Of course the print_r() is only so I can see what the code is producing. The output looks like this:
html Output
Thanks again for you assistance!
Cheers,
shackleton
Your approach is a bit heavy-handed with the foreach loops. I have prepared a shorter way to accomplish your task.
Using this array:
$FILES=array(
"file1"=>array("type"=>array("text/plain")),
"file2"=>array("type"=>array("image/tiff")),
"file3"=>array("type"=>array("")),
"file4"=>array("type"=>array("image/png")),
"file5"=>array("type"=>array("image/gif")),
"file6"=>array("type"=>array("image/jpeg"))
);
You can have your output with these two one-liners:
$simple_images=array_column(array_column($FILES,"type"),0);
var_export($simple_images);
echo "\n";
$difference=array_filter($simple_images,function($v){return strpos($v,"image")===false;});
var_export($difference);
Output:
array (
0 => 'text/plain',
1 => 'image/tiff',
2 => '',
3 => 'image/png',
4 => 'image/gif',
5 => 'image/jpeg',
)
array (
0 => 'text/plain',
2 => '',
)
Referring to your preg_grep() function, it is best to avoid using regex when another string manipulation will suffice. This is will improve performance.
I am fairly new to PHP and have been working on looping through this array for days...sigh...
http://pastebin.com/Rs6P4e4y
I am trying to get the name and headshot values of the writers and directors array.
I've been trying to figure out the foreach function to use with it, but have had no luck.
<?php foreach ($directors as $key => $value){
//print_r($value);
}
?>
Any help is appreciated.
You looking for some such beast? You didn't write how you wanted to process them, but hopefully this helps you.
$directors = array();
foreach( $object->people->directors as $o )
$directors[] = array( 'name' => $o->name, 'headshot' => $o->images->headshot );
$writers = array();
foreach( $object->people->writers as $o )
$writers[] = array( 'name' => $o->name, 'headshot' => $o->images->headshot );
var_dump( $directors );
var_dump( $writers );
Last note, if there's no guarantee that these members are set, you use isset before any dirty work.
Hope this helps.
Use -> to access properties of the objects.
foreach ($directors as $director) {
echo 'Name: ' . $director->name . "\n";
echo "Headshot: " . $director->images->headshot . "\n";
}
Your solution has already been posted, but I want to add something:
This isn't an Array, it's an object. Actually the directors property of the object is an Array. Look up what an object is and what associative arrays are!
Objects have properties, arrays have keys and values.
$object = new stdClass();
$object->something = 'this is an object property';
$array = new array();
$array['something'] = 'this is an array key named something';
$object->arrayproperty = $array;
echo $object->arrayproperty['something']; //this is an array key named something
Good luck with learning PHP! :)
Having variable $foo, which is an object, you can access property bar using syntax:
$foo->bar
So if you have an array od directors named $directors, you can simply use it the same way in foreach:
foreach ($directors as $value){
echo $value->name." ".$value->images->headshot;
}
I have the following snippet of code that is creating the following array...
while ($stmt->fetch()) {
foreach($row as $key => $val) {
$x[$key] = $val;
}
$results[] = $x;
}
Results in the follow array:
Array ( [0] => Array ( [cap_login] => master [cap_pword] => B-a411dc195b1f04e638565e5479b1880956011badb73361ca ) )
Basically I want to extract the cap_login and cap_pword values for testing. For some reason I can't get it!
I've tried this kind of thing:
echo $results[$cap_login];
but I get the error
Undefined variable: cap_login
Can someone put me right here?
Thanks.
cap_login is in an array within $results so you would have to do $results[0]['cap_login']
You would have to do the following:
echo $x[0]['cap_login'] . '<br />';
echo $x[0]['cap_pword'];
The reson $results[$cap_login] wont work is because there isn't a variable called $cap_login, there is a string called cap login. In addition, there isn't a key in $results called $cap_login. There is a value in $results called 'cap_login'
I am trying to build an array and I am looping through the values of an XML document, I have everything pulling out great using xpath, here's my code:
function parseAccountIds($xml) {
$arr = array();
foreach($xml->entry as $k => $v) {
$acctName = $v->title;
$prop = $v->xpath('dxp:property');
foreach($prop as $k1 => $v1) {
if($v1->attributes()->name == "ga:accountId")
$acctId = (string) $v1->attributes()->value;
else if($v1->attributes()->name == "ga:profileId")
$profileId = (string) $v1->attributes()->value;
}
echo "profile id ".$profileId;
echo "<BR>";
echo "acctName ".$acctName;
echo "<BR>";
$subArray = array($acctName => $profileId);
print_r($subArray);
$arr[] = array($acctId => $subArray);
}
print_r($arr);
return json_encode($arr);
}
The most important bit is where I print_r subArray. I can see acctName and profileId print, but then subArray is empty. For Example:
profile id 45580
acctName accountName1
Array
(
)
profile id 4300
acctName accountName2
Array
(
)
profile id 4338
acctName accountName3
Array
(
)
How are these values not being inserted? I've been looking at the code for a while now, and I'm a bit confused.
Any suggestions would really help,
Thanks!
try this:
$subArray[$acctName] = $profileId;
instead of
$subArray = array($acctName => $profileId);
$v->title is actually a SimpleXMLObject still!
I forgot to cast it as a string, when I tried to make it the index in the array, it freaked out, geez I spent a whole hour on this!
Thanks for your suggestions guys :P