I have keys and values as follows :
[store_id] => 1
[store_name] => StarShop
[store_phone] => 62-22-8383838
[store_email] => admin#starshop.com
I use this to make objects with $this from the above arrays
foreach($above_array as $key => $value){
$this->$key = $value;
}
echo $this->store_name; // this does not work, please help
You cannot use $this->, if you are not inside a class:
<?php
$a = array(
'store_id' => 1,
'store_name' => 'StarShop',
'store_phone' => '62-22-8383838',
'store_email] => admin#starshop.com',
);
$obj = new StdClass; // create new object
foreach($a as $key => $value){ // iterate as before
$obj->$key = $value; // add properties to object
}
echo $obj->store_name;
?>
Demo
Related
I have a loop of the following kind:
foreach ($values as $key => $value) {
$attrs = array('NAME' => $key);
myproc ($attrs);
......
}
Where in myproc the first parameter is defined by reference:
function myproc (& attrs) { .... }
myproc adds the passed value to some structure.
The trouble with this is that at loop end, all the arrays added to the generated structure contains the same value, the last value extracted from the loop.
I tried also something like this :
foreach ($values as $key => $value) {
$attrs = array('NAME' => $key);
$copy = $attrs;
myproc ($copy);
......
}
but the result is the same. I'not allowed to modify the procedure. Any suggestions?
Based on the comment below your question, it seems that the problem is that you are passing a reference and this reference gets updated in the loop, leading to updates in the object you are generating in your function.
To avoid this, you need to unset the variable after the function call so that the link between the value in your object and the referenced variable is broken:
foreach ($values as $key => $value) {
$attrs = array('NAME' => $key);
myproc ($attrs);
// unset the variable so that newer values of it will have no effect
// on the object generated in `myproc`
unset($attrs);
......
}
Also see the manual.
<?php
foreach(['red','pink','green'] as $colour) {
$attrs = ['colour' => $colour];
if(colourToAction($attrs)) {
$results[] = $attrs;
}
}
var_export($results);
function colourToAction(&$attrs) {
$actions = ['red'=>'stop','amber'=>'wait', 'green' => 'go'];
if(isset($attrs['colour']) && isset($actions[$attrs['colour']])){
$attrs['action'] = $actions[$attrs['colour']];
return true;
}
}
Output:
array (
0 =>
array (
'colour' => 'red',
'action' => 'stop',
),
1 =>
array (
'colour' => 'green',
'action' => 'go',
),
)
I want to print all the properties from an object.
Is there a way to use the key value as a property value of a object? instead of using get_object_vars.
Error
Undefined property: stdClass::$key
Update Example
foreach ($arrayOfArrays as $key => $arrayOfValues) {
foreach($arrayOfValue as $key => $value){
$object = (object) $value;
echo $object->$key;
}
}
Example of $arrayOfValues
Array
(
[key1] => "value1"
[key2] => "value2"
)
Example of $value
stdClass Object
(
[scalar] => "value1"
)
stdClass Object
(
[scalar] => "value2"
)
I think that in your case it was a simple typo:
$arrayOfArrays = [[
'key1' => 'value 1',
'key2' => 'value 2',
]];
foreach ($arrayOfArrays as $key => $arrayOfValues) {
$object = (object) $arrayOfValues;
echo $object->key1; // you ommited the 1;
}
As the other mentioned you can use directly the array. No need to convert it to object:
foreach ($arrayOfArrays as $key => $arrayOfValues) {
echo $arrayOfValues['key1'];
}
If you want to display all the keys of that array you can simply use something like:
foreach ($arrayOfArrays as $key => $arrayOfValues) {
$object = (object) $arrayOfValues;
foreach (array_keys($arrayOfValues) as $unkownKey) {
echo $object->$unkownKey;
}
}
You should use scalar instead of key:
<?php
$array = ['hi', 'there'];
foreach ($array as $key => $value) {
$object = (object) $value;
// print_r($object);
echo $object->scalar;
}
Working example here.
As docs say on:
For any other value, a member variable named scalar will contain the value.
http://php.net/manual/en/language.types.object.php
At this time, we still have to guess at the data structure. Here is my best guess at a complete example:
$array = array(
(object) "value1",
(object) "value2"
);
foreach ($array as $name => $array_value) {
$object = (object) $array_value;
foreach ($object as $property => $value) {
echo $object->$property . "\n";
}
}
Try it yourself at repl.it
I have an array, looking like this:
[lund] => Array
(
[69] => foo
)
[berlin] => Array
(
[138] => foox2
)
[tokyo] => Array
(
[180] => foox2
[109] => Big entrance
[73] => foo
)
The thing is that there were duplicate keys, so I re-arranged them so I can search more specifically, I thought.
Previously I could just
$key = array_search('foo', $array);
to get the key but now I don't know how.
Question: I need key for value foo, from tokyo. How do I do that?
You can get all keys and value of foo by using this:
foreach ($array as $key => $value) {
$newArr[$key] = array_search('foo', $value);
}
print_r(array_filter($newArr));
Result is:
Array
(
[lund] => 69
[tokyo] => 109
)
If you don't mind about the hard code than you can use this:
array_search('foo', $array['tokyo']);
It just a simple example, you can modify it as per your requirement.
Try this
$a = array(
"land"=> array("69"=>"foo"),
"land1"=> array("138"=>"foo1"),
"land2"=> array('180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'),
);
//print_r($a);
$reply = search_in_array($a, "foo");
print_r($reply);
function search_in_array($a, $search)
{
$result = array();
foreach($a as $key1 => $array ) {
foreach($array as $k => $value) {
if($value == "$search") {
array_push($result,"{$key1}=>{$k}");
breck;
}
}
}
return $result;
}
This function will return the key or null if the search value is not found.
function search($searchKey, $searchValue, $searchArr)
{
foreach ($searchArr as $key => $value) {
if ($key == $searchKey && in_array($searchValue, $value)) {
$results = array_search($searchValue, $value);
}
}
return isset($results) ? $results : null;
}
// var_dump(search('tokyo', 'foo', $array));
Since Question: I need key for value foo, from tokyo. How do i do that?
$key = array_search('foo', $array['tokyo']);
As a function:
function getKey($keyword, $city, $array) {
return array_search($keyword, $array[$city]);
}
// PS. Might be a good idea to wrap this array in an object and make getKey an object method.
If you want to get all cities (for example to loop through them):
$cities = array_keys($array);
I created solution using array iterator. Have a look on below solution:
$array = array(
'lund' => array
(
'69' => 'foo'
),
'berlin' => array
(
'138' => 'foox2'
),
'tokyo' => array
(
'180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'
)
);
$main_key = 'tokyo'; //key of array
$search_value = 'foo'; //value which need to be search
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key => $value) {
$keys = array();
if ($value == $search_value) {
$keys[] = $key;
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$keys[] = $iterator->getSubIterator($i)->key();
}
$key_paths = array_reverse($keys);
if(in_array($main_key, $key_paths) !== false) {
echo "'{$key}' have '{$value}' value which traverse path is: " . implode(' -> ', $key_paths) . '<br>';
}
}
}
you can change value of $main_key and $serch_value according to your parameter. hope this will help you.
<?php
$lund = [
'69' => 'foo'
];
$berlin = [
'138' => 'foox2'
];
$tokyo = [
'180' => 'foox2',
'109' => 'Big entrance',
'73' => 'foo'
];
$array = [
$lund,
$berlin,
$tokyo
];
echo $array[2]['180']; // outputs 'foox2' from $tokyo array
?>
If you want to get key by specific key and value then your code should be:
function search_array($array, $key, $value)
{
if(is_array($array[$key])) {
return array_search($value, $array[$key]);
}
}
echo search_array($arr, 'tokyo', 'foo');
try this:
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'On');
$array=array("lund" => array
(
69 => "foo"
),
"berlin" => array
(
138 => "foox2"
),
"tokyo" => array
(
180 => "foox2",
109 => "Big entrance",
73 => "foo"
));
function search($array, $arrkey1, $arrvalue2){
foreach($array as $arrkey=>$arrvalue){
if($arrkey == $arrkey1){
foreach($arrvalue as $arrkey=>$arrvalue){
if(preg_match("/$arrvalue/i",$arrvalue2))
return $arrkey;
}
}
}
}
$result=search($array, "tokyo", "foo"); //$array=array; tokyo="inside array to check"; foo="value" to check
echo $result;
You need to loop through array, since its 2 dimensional in this case. And then find corresponding value.
foreach($arr as $key1 => $key2 ) {
foreach($key2 as $k => $value) {
if($value == "foo") {
echo "{$k} => {$value}";
}
}
}
This example match key with $value, but you can do match with $k also, which in this case is $key2.
I need to assign in an associative array a number as key name, but if I do:
// Places (generated by mysql)
$places = array (
0 => '1234',
1 => '2345'
);
// Week stats (generated by mysql)
$week = array (
1234 =>
array (
0 =>
array (
'iid' => '1234',
'mid' => 'xxxxxxxx',
'name' => 'Name1',
),
1 =>
array (
'iid' => '1234',
'mid' => 'xxxxxxxx',
'name' => 'Name3',
)
),
2345 =>
array (
0 =>
array (
'iid' => '2345',
'mid' => 'xxxxxxxx',
'name' => 'Name2',
),
2 =>
array (
'iid' => '2345',
'mid' => 'xxxxxxxx',
'name' => 'Name4',
)
)
);
foreach($places as &$place) {
echo $place;
$i = 0;
foreach($week[$i] as &$value) {
echo $value["name"];
$i++;
}
}
it doesn't work:
http://codepad.viper-7.com/Y1g37t
because seems I should call it with:
echo $arr[<specific index>];
Instead I need to set "1234" and "2345" as strings, like this array:
$arr = Array("foo" => "bar");
So I can call it with
$arr[0] // bar
How can I do?
Solution
Thanks to #kirilloid
i use this code:
$vararr = array_keys($week);
$key = $vararr[$i];
To get the key
It because it's an map and map associates values to keys so you have to do this :
<?php
$myNumber = 1234;
$myValue = "foo";
$arr = Array( $myNumber => $myValue );
echo $arr[1234];
?>
And don't forget to replace the ":" at your first line !
To iterate on a "map" you can use the foreach function :
foreach($arr as $key=>$value) {
echo $key;
echo $value;
}
This should display your key and the value associated :
1234
foo
Here is the difference with a simple array:
$array = array("foo", "bar", "hallo", "world");
echo $array[0];
You may either use array_keys:
echo $arr[array_keys($arr)[0]];
or reset and current:
reset($arr);
echo current($arr);
There is no problem here - this is how it is supposed to work.
If you create an array like this:
$myNumber = 1234;
$myValue = "foo";
$arr = Array( $myNumber => $myValue );
then the index of the element is 1234, not 0.
You can retrieve it with echo $arr[1234]
If you need to loop over the array you can do so with
foreach($arr as $key=>$value) {
// do something with $value
}
There is no problem. As the value of $myNumber is 1234, you should access the array element like this:
echo $arr[1234];
If you need to access them in a foor loop you can get the keys as an array:
$keys = array_keys($arr);
$keys_count = count($keys);
for ($i=0; i<$keys_count; $i++) {
echo $arr[$keys[$i]];
}
I have an array like this:
$arr = array(
$foo = array(
'donuts' => array(
'name' => 'lionel ritchie',
'animal' => 'manatee',
)
)
);
Using that magic of the 'SPL Recursive Iterator' and this code:
$bar = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
foreach($bar as $key => $value)
{
echo $key . ": " . $value . "<br>";
}
I can traverse the multidimensional array and return the key => value pairs, such as:
name: lionel ritchie
animal: manatee
However, I need to return the PARENT element of the current iterated array as well, so...
donuts name: lionel richie
donuts animal: manatee
Is this possible?
(I've only become aware of all the 'Recursive Iterator' stuff, so if I'm missing something obvious, I apologise.)
You can access the iterator via getSubIterator, and in your case you want the key:
<?php
$arr = array(
$foo = array(
'donuts' => array(
'name' => 'lionel ritchie',
'animal' => 'manatee',
)
)
);
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
foreach ($iterator as $key => $value) {
// loop through the subIterators...
$keys = array();
// in this case i skip the grand parent (numeric array)
for ($i = $iterator->getDepth()-1; $i>0; $i--) {
$keys[] = $iterator->getSubIterator($i)->key();
}
$keys[] = $key;
echo implode(' ',$keys).': '.$value.'<br>';
}
?>