I have an array that give objects back like this:
array (size=61)
0 =>
object(Xxx\Car)[602]
private 'id' => int 53
private 'name' => string 'Volkswagen' (length=10)
1 =>
object(Xxx\Car)[594]
private 'id' => int 43
private 'name' => string 'Toyota' (length=6)
2 =>
object(Xxx\Car)[595]
private 'id' => int 32
private 'name' => string 'BMW' (length=3)
How can I convert the array to so that the id become the key and the value the description, like this:
array (size=61)
53 => 'Volkswagen'
43 => 'Toyota'
32 => 'BMW'
I've tried
$cars = array();
foreach ($result as $key => $value) {
$cars[$value['id']] = $value['name'];
}
But that doesn't work.
You are treating your objects as if they were arrays.
$array['key'] is the notation for accessing an element in an array, but $object->key is the one for an object.
Try this :
$cars = array();
foreach ($result as $key => $value) {
$cars[$value->id] = $value->name;
}
EDIT : If that doesn't work (due to the private nature of the elements), you might have to declare functions like getID() and getName() in your object class file, and use them as such :
$cars = array();
foreach ($result as $key => $value) {
$cars[$value->getID()] = $value->getName();
}
Use the $arr = get_object_vars($obj); function. It converts an object to an array.
Related
I'm trying to escape values from a multidimensional array for my database class. The code I have currently:
// Function to escape array values
private function esc_sql_arr(array $to_esc) {
$clean_arr = array();
foreach($to_esc as $k => $v) {
if(is_array($to_esc[$k])) {
foreach($to_esc[$k] as $key => $val) {
$k = $this->_mysqli->real_escape_string($k);
$key = $this->_mysqli->real_escape_string($key);
$val = $this->_mysqli->real_escape_string($val);
$clean_arr[$k][$key] = $val;
}
} else {
$k = $this->_mysqli->real_escape_string($k);
$v = $this->_mysqli->real_escape_string($v);
$clean_arr[$k] = $v;
}
}
return $clean_arr;
}
I'm assuming the following input example (it should be 'where', I purposely changed it to test the above method):
$args = array(
"table" => "t'1",
"data" => array(
"c'sf4;(" => 'xdfbxdrf',
'c2' => "'t'est'",
'cs' => 'hey'
),
"whe're" => array(
'test' => 'test1'
)
);
var_dump:
array (size=3)
'table' => string 't\'1' (length=4)
'data' =>
array (size=3)
'c\'sf4;(' => string 'xdfbxdrf' (length=8)
'c2' => string '\'t\'est\'' (length=10)
'cs' => string 'hey' (length=3)
'whe\'re' =>
array (size=1)
'test' => string 'test1' (length=5)
The code works without any issue. However, is this the right way to escape a multidimensional array?
I believe I might not have to use this method since I use prepared statements. Any feedback on using this is welcome.
I want the array to merge into a key value pair. look at the example below
Here is my code and array $aExtraFilter
array (size=4)
0 =>
array (size=2)
'key' => string 'CookTech' (length=8)
'value' => string 'Broil' (length=5)
1 =>
array (size=2)
'key' => string 'CookTech' (length=8)
'value' => string 'Pan Fry' (length=7)
2 =>
array (size=2)
'key' => string 'CookSkills' (length=10)
'value' => string 'Intro' (length=5)
3 =>
array (size=2)
'key' => string 'CookSkills' (length=10)
'value' => string 'Knife Skills' (length=12)
Here is my code:
$aExtraFilter2 = [];
$extrafilterkey = '';
$extrafiltervalue = [];
foreach ($aExtraFilter as $key => $value) {
$extrafilterkey = $value['key'];
$aExtraFilter2[$extrafilterkey] = [];
array_push($extrafiltervalue, $value['value']);
$aExtraFilter2[$extrafilterkey] = implode(',', $extrafiltervalue);
}
var_dump($aExtraFilter2);
the output is :
array (size=2)
'CookTech' => string 'Broil,Pan Fry' (length=13)
'CookSkills' => string 'Broil,Pan Fry,Intro,Knife Skills' (length=32)
I want it to look like this:
array (size=2)
'CookTech' => string 'Broil,Pan Fry' (length=13)
'CookSkills' => string 'Intro,Knife Skills' (length=32)
I think I'm almost there but I guess I need some help.
This line does nothing because it is superseded just a bit later as the same variable is being set:
$aExtraFilter2[$extrafilterkey] = [];
This line appends to the array regardless of what you have as $value['key'], which is why you get all keys lumped together in the output:
array_push($extrafiltervalue, $value['value']);
This will produce a desired output:
// fill array of arrays
$aExtraFilter2 = [];
foreach ($aExtraFilter as $key => $value) {
if (!array_key_exists($value['key'], $aExtraFilter2)) $aExtraFilter2[$value['key']] = [];
$aExtraFilter2[$value['key']][] = $value['value'];
}
// convert to string (if needed at all, depends on what you're doing later)
foreach ($aExtraFilter2 as $key => $set) {
$aExtraFilter2[$key] = join(',', $set);
}
The typical way to code this is by creating a temporary structure, based on the key and comprising an array with the values:
$tmp = [];
foreach ($aExtraFilter as $pair) {
$tmp[$pair['key']][] = $pair['value'];
}
The structure would look like this afterwards:
[
'CookTech' => ['Broil', 'Pan Fry'],
'CookSkills' => ['Intro', 'Knife Skills'],
]
Then, you map that array against the representation you want to have:
$aExtraFilter2 = array_map(function($values) {
return join(',', $values);
}, $tmp);
See also: array_map()
I am trying to remove pieces of a multidimensional array if a certain condition is met. The array can be as shown below, call it $friends:
array (size=3)
0 =>
array (size=1)
0 =>
object(stdClass)[500]
public 'id' => int 2
public 'first_name' => string 'Mary' (length=4)
public 'last_name' => string 'Sweet' (length=5)
1 =>
array (size=1)
0 =>
object(stdClass)[501]
public 'id' => int 9
public 'first_name' => string 'Joe' (length=3)
public 'last_name' => string 'Bob' (length=3)
2 =>
array (size=1)
0 =>
object(stdClass)[502]
public 'id' => int 1
public 'first_name' => string 'Shag' (length=4)
public 'last_name' => string 'Well' (length=4)
I have a function called is_followed, that let's me see if the id of one of the people in the array is being followed by the "user". The code I am trying is:
//remove followed friends from the $friends array
$i=0;
foreach($friends as $friend) {
foreach($friend as $f) {
if(Fanfollow::is_followed($id,$f->id)) {
unset($friend[$i]);
}
}
$i++;
}
The $id is the id of the current user.
However, this is not working. I know that using unset on $friend and not $friends is probably the issue. But using unset on $friends also won't work, because it is the higher level array. Any ideas? Thank you.
If you're trying to take down the first parent keys, use the first foreach keys instead:
foreach($friends as $i => $friend) {
// ^ assign a key
foreach($friend as $f) {
if(Fanfollow::is_followed($id,$f->id)) {
unset($friends[$i]);
// unset this
}
}
}
Or if only for that single friend:
foreach($friends as $friend) {
foreach($friend as $i => $f) {
// ^ this key
if(Fanfollow::is_followed($id,$f->id)) {
unset($friend[$i]);
// unset this
}
}
}
array_filter comes to the rescue:
array_filter($friend,
function($f) use($id) { return Fanfollow::is_followed($id,$f->id)); }
);
Though the solution with foreach is legit, array_filteris much more clear and sematically correct.
So far my var_dump() of a $records array looks like:
array (size=1)
25 =>
array (size=1)
0 =>
object(stdClass)[51]
public 'id' => 25
public 'name' => info...
public 'surname' => info...
I wan't to change that 0 index name to object id (25) name but it just adds one more dimension above my current one. This is how I do it:
foreach ($records as $value) {
$records = array($value->id=>$records);
}
I want my array to look like this though:
array (size=1)
25 =>
object(stdClass)[51]
public 'id' => 25
public 'name' => info...
public 'surname' => info...
Updating keys so they equal the ID:
$tmp= array();
foreach ($records as $value) {
$tmp[$value->id] = $value;
}
$records = $tmp;
$array = (object)array(
'name' => 'David',
'friends' => (object)array(
(object)array('name' => 'Max'),
(object)array('name' => 'Jian')
)
);
var_dump($array);
I want to learn how to use stdClass function to get the same result, don't want to use (object) before each array, convert cause some resource, and I know json_encode and json_decode can make it, just want to learn how stdClass make nested structure.
There's a trick with json_encode() to easily get this:
$array = array(
'foo' => array('bar'=>'a', 'baz'=>'b'),
'feo' => 'bee',
'boo' => array('a'=>array('x', 'y'), 'b'=>array('z'))
);
$object = json_decode(json_encode($array));
Update
If you don't want to use JSON function, you can handle your array recursively, like:
function getStdObject(array $data)
{
foreach($data as &$item)
{
if(is_array($item))
{
$item = getStdObject($item);
}
}
return (object)$data;
}
$array = array(
'foo' => array('bar'=>'a', 'baz'=>'b'),
'feo' => 'bee',
'boo' => array('a'=>array('x', 'y'), 'b'=>array('z'))
);
$object = getStdObject($array));
This class is available at: http://php.net/manual/en/arrayobject.construct.php#111192
/**
* #author Iltar van der Berg
* #version 2.0.0
*/
class RecursiveArrayObject extends ArrayObject
{
/**
* overwrites the ArrayObject constructor for
* iteration through the "array". When the item
* is an array, it creates another self() instead
* of an array
*
* #param Array $array data array
*/
public function __construct(Array $array)
{
foreach($array as $key => $value) {
if(is_array($value)){
$value = new static($value);
}
$this->offsetSet($key, $value);
}
}
/**
* returns Array when printed (like "echo array();")
* instead of an error
*
* #return string
*/
public function __ToString()
{
return 'Array';
}
}
Usage:
$a = array(
'one' => array(
'hello','world'
),
'two' => array(
'lorem','ipsum'
)
);
var_dump($a);
$o = new RecursiveArrayObject($a);
var_dump($o);
Yields:
array (size=2)
'one' =>
array (size=2)
0 => string 'hello' (length=5)
1 => string 'world' (length=5)
'two' =>
array (size=2)
0 => string 'lorem' (length=5)
1 => string 'ipsum' (length=5)
object(RecursiveArrayObject)[1]
public 'one' =>
object(RecursiveArrayObject)[2]
string 'hello' (length=5)
string 'world' (length=5)
public 'two' =>
object(RecursiveArrayObject)[3]
string 'lorem' (length=5)
string 'ipsum' (length=5)