$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)
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 would like to check if the value of a standard class object has a value of 'None'. The object is a PDO and pulls data from the database.
Here is the data from a var_dump:
array (size=1)
0 =>
object(stdClass)[8]
public 'Subid' => string '1' (length=1)
public 'id' => string '27' (length=2)
public 'english' => string 'English Standard' (length=16)
public 'maths' => string 'Mathematics General 2' (length=21)
public 'hsie1' => string 'Modern History' (length=14)
public 'science1' => string 'Biology' (length=7)
public 'science2' => string 'None' (length=4)
public 'science3' => string 'None' (length=4)
public 'tech1' => string 'Agriculture' (length=11)
public 'tech2' => string 'None' (length=4)
public 'extension' => string 'None' (length=4)
public 'arts1' => string 'None' (length=4)
public 'arts2' => string 'Dance' (length=5)
public 'pdhpe1' => string 'None' (length=4)
public 'vet1' => string 'None' (length=4)
public 'start_time' => string '2016-11-15 19:54:08' (length=19)
Is it possible to loop through the keys and test the values?
You can foreach over an array and the public properties of an object
So
foreach ( $array as $obj ) {
foreach ( $obj as $prop => $val ) {
if ( $val == 'None' ) {
echo $prop . ' = ' . $val;
}
}
}
EDIT:
I dont see why you had to change anything here is a quick test I ran
$o = new stdClass;
$o->p1 = 1;
$o->p2 = 'two';
$o->p3 = 'None';
$array = array($o);
var_dump($array);
foreach ( $array as $obj ) {
foreach ( $obj as $prop => $val ) {
if ( $val == 'None' ) {
echo $prop . ' = ' . $val;
}
}
}
And the results were
array(1) {
[0] =>
class stdClass#1 (3) {
public $p1 => int(1)
public $p2 => string(3) "two"
public $p3 => string(4) "None"
}
}
p3 = None
$a = ['foo' => 'bar'];
If I want to add new elements in this array I would usually write this
$a['foo2'] = 'bar2';
$a['foo3'] = 'bar3';
$a['foo4'] = 'bar4';
Is there some other syntax so I can add elements like this without overwriting $a?
$a = [ 'foo2' => 'bar2',
'foo3' => 'bar3',
'foo4' => 'bar4'];
You can also do something like this:
$arr1 = array('foo2' => 'bar2');
$arr2 = array('foo3' => 'bar3');
$arr3 = $arr1 + $arr2;
You can use array_merge to add an array to the end of another array.
$a = array_merge($a, $b);
where $b is:
$b = [ 'foo2' => 'bar2',
'foo3' => 'bar3',
'foo4' => 'bar4'];
Or just do:
$a = ['foo' => 'bar'];
$a = array_merge([$a,'foo2' => 'bar2',
'foo3' => 'bar3',
'foo4' => 'bar4'];
Will return what you want.
You could create a simple Function for that like so:
<?php
/**
* #param $mainArray => THE ARRAY TO WHICH OTHER ELEMENTS (INCL. ARRAYS/OBJECTS) SHOULD BE ADDED
* #param $data => A KEY-VALUE PAIR ARRAY OR A NORMAL STRING/NUMBER
* #return array
*/
function arrayAdd(&$mainArray, $data){
if(is_array($data)){
foreach($data as $k=>$v){
$mainArray[$k] = $v;
}
}else if(is_string($data)){
$mainArray[] = $data;
}
return $mainArray;
}
// CREATE A OBJECT (TO SHOW IT COULD ALSO HANDLE THAT AS WELL)
$obj = new stdClass();
$obj->name = 'Some Name';
$obj->tel = '+1 202 532 00 00 00';
// THE MAIN ARRAY TO WHICH OTHER ELEMENTS SHOULD BE ADDED
$main = ['foo1' => 'bar1', 'foo2' => 'bar2'];
// A COLLECTION OF DATA TO ADD TO $main
$data = [
'one' => 'Un',
'two' => 'Deux',
'three' => 'Trois',
'four' => 'Quart',
'obj' => $obj,
];
// CALL THE FUNCTION AND PASS THE PARAMETERS
var_dump( arrayAdd($main, $data) );
// YIELDS::
array (size=7)
'foo1' => string 'bar1' (length=4)
'foo2' => string 'bar2' (length=4)
'one' => string 'Un' (length=2)
'two' => string 'Deux' (length=4)
'three' => string 'Trois' (length=5)
'four' => string 'Quart' (length=5)
'obj' =>
object(stdClass)[1]
public 'name' => string 'Some Name' (length=9)
public 'tel' => string '+1 202 532 00 00 00' (length=19)
How about this ?
I think it is simplest to add element into an array
<?php
$cart = [];
//to add one
array_push($cart, 13);
// to add multiple
array_push($cart, 13,14,15);
?>
Hello i am trying to combine two php array.
First one
array (size=13)
0 =>
object(stdClass)[30]
public 'ID' => string '1' (length=1)
public 'name' => string 'html5' (length=5)
public 'img' => string 'HTML5.png' (length=9)
1 =>
object(stdClass)[31]
public 'ID' => string '2' (length=1)
public 'name' => string 'css3' (length=4)
public 'img' => string 'css.png' (length=7)
2 =>
object(stdClass)[32]
public 'ID' => string '3' (length=1)
public 'name' => string 'php' (length=3)
public 'img' => string 'php1.png' (length=8)
3 =>
object(stdClass)[33]
public 'ID' => string '4' (length=1)
public 'name' => string 'java script' (length=11)
public 'img' => string 'javascript.png' (length=14)
Second one
array (size=3)
0 =>
object(stdClass)[26]
public 'ID' => string '1' (length=1)
public 'IDuser' => string '1' (length=1)
public 'IDskill' => string '1' (length=1)
1 =>
object(stdClass)[27]
public 'ID' => string '2' (length=1)
public 'IDuser' => string '1' (length=1)
public 'IDskill' => string '3' (length=1)
2 =>
object(stdClass)[28]
public 'ID' => string '3' (length=1)
public 'IDuser' => string '1' (length=1)
public 'IDskill' => string '4' (length=1)
ID from first array is equal to IDskill from second array. I am trying to combine to create new array if IDskill and ID are same, with something like this in new array
public 'ID' => string '1' (length=1)
public 'name' => string 'html5' (length=5)
public 'img' => string 'HTML5.png' (length=9)
===>New field public 'MATCH' => string '1' (length=9)
use array_merge() function
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
or
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
Try this ( where a1 is first array and a2 is second one and $result is final, merged array ):
$result = array();
$n=0;
foreach($a1 as $k=>$v) {
if (isset($v->ID) && isset($a2[$n]->ID) && $v->ID==$a2[$n]->ID) {
$result[$n]=$v;
$result[$n]->MATCH=1;
}
$n++;
}
print_r($result);
You could use array_map and anonymous functions:
<?php
$first_array = array(...);
$second_array = array(...);
// Anonymous function to extract the IDskills from the second array:
$get_IDs = function($element) {
return($element->IDskill);
};
// Array of (just) IDskills of the second array:
$IDs = array_map($get_IDs, array_filter($second_array, function($element) {
// Anonymous function to filter $second_array elements without IDskill:
return(isset($element->IDskill));
}));
// Another anonymous function that returns a new array with elements from
// $first_array with the new MATCH property.
// use(&$IDs) makes $IDs available inside the function scope:
$check_match = function($element) use(&$IDs) {
// We use clone because we don't want to modify the original array values:
$match_element = clone $element;
if(isset($match_element->ID))
$match_element->MATCH = in_array($match_element->ID, $IDs);
else
$match_element->MATCH = false;
return($match_element);
};
$match = array_map($check_match, $first_array);
?>
If you don't want to use the two first anonymous functions or don't want to create the $IDs array you can replace use(&$IDs) for use(&$second_array) and the line:
$match_element->MATCH = in_array($match_element->ID, $IDs);
for a loop that iterates through $second_array elements to check whether any of them has an IDskill equal to $match_element->ID.
Moreover, you may not need to check if IDskill and ID exist if all the elements in the arrays have the same properties.
let me add my two cents, how to find element matching ID from the 1st array in the second one
$tmp = array_filter($array2, function($ar2) use ($ID) { return $ar2->IDskill === $ID; });
if ($tmp) // Found
else // Not found
all code may be
result = array()
foreach ($array1 as $item) {
$ID = $item->ID;
$tmp = array_filter($array2, function($ar2) use ($ID) { return $ar2->IDskill === $ID; });
if ($tmp) { // Found
$tmp = $item;
$tmp->MATCH = 1;
result[] = $tmp;
}
}
I have variable $related witch is stdCalss object and i want to convert it with one foreach loop in to reffrence array.
Var_dump of Object $related:
array (size=19)
0 =>
object(stdClass)[20]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1567' (length=4)
1 =>
object(stdClass)[21]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1562' (length=4)
2 =>
object(stdClass)[22]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1564' (length=4)
3 =>
object(stdClass)[23]
public 'id_product' => string '1568' (length=4)
public 'related' => string '1410' (length=4)
4 =>
object(stdClass)[24]
public 'id_product' => string '111' (length=3)
public 'related' => string '77' (length=2)
5 =>
object(stdClass)[25]
public 'id_product' => string '111' (length=3)
public 'related' => string '1610' (length=4)
Php code:
foreach ($related AS $r){
????
}
var_dump($rels);
Wished Output:
$rels = array(
'1568'=>'1567, 1562, 1564, 1410',
'111'=>'77,1610'
);
Build a temporary array and implode it:
foreach($related AS $r) {
$temp[$r->id_product][] = $r->related;
$rels[$r->id_product] = implode(', ', $temp[$r->id_product]);
}
print_r($rels);
$rels = array ();
foreach ($related as $r){
$rels[$r->id_product] .= $r->related . ","; // put all of them with respective key together
}
$rels = array_map(
function ($a) {
$a = preg_replace('~,(?!.*,)~', '', $a);
return $a;
}
,$rels); // remove last commas
var_dump($rels);
Try,
$rels = array();
foreach($related as $r){
$rels[$r->id_product] .= $r->related.', ';
}
array_walk_recursive($related, function(&$item){
$item = rtrim($item,', ');
});
From the PHP docs: http://php.net/manual/en/language.types.type-juggling.php