I have an associative array like this
$imagePaths = array(
'logo' => "logo.jpg",
'facebook-logo' => "facebook-icon.jpg",
'twitter-logo' => "twitter-icon.jpg",
'linkedin' => "linkedIn.jpg"
);
for me to call logo, I use below code
$ClassInstance->imagePaths['logo'];
But I would also like to be able to call it using
$ClassInstance->imagePaths[0];
Is there anyway to do this?
You can achieve this with array_keys():
$keys = array_keys($imagePaths);
$ClassInstance->imagePaths[$keys[0]];
You could store a second array using array_values():
$imagePathsKeyed = array_values($imagePaths);
EDIT: I've expanded the example code to help here
<?php
class SomeObject
{
public $imagePaths;
public $keyedImagePaths;
public function __construct()
{
$this->imagePaths = array(
'logo' => "logo.jpg",
'facebook-logo' => "facebook-icon.jpg",
'twitter-logo' => "twitter-icon.jpg",
'linkedin' => "linkedIn.jpg"
);
$this->keyedImagePaths = array_values($this->imagePaths);
}
}
$classInstance = new SomeObject();
// logo.jpg
echo $classInstance->imagePaths['logo'];
// logo.jpg
echo $classInstance->keyedImagePaths[0];
Related
I have an array like so:
$cars = array(
'type' => array(
'brand' => array(
'car' => 'Honda',
),
),
);
And I also have a string like so:
$path = "type][brand][car";
I'd like to return a value of car from $cars array using $path string, but of course this won't work:
echo $cars[$path];
The output I'd like to have is: "Honda". How this should be done?
Here is basicly what I understood you want to achieve in a simple function, that uses the parents array to get a nested value:
<?php
$cars = array(
'type' => array(
'brand' => array(
'car' => 'Honda',
),
),
);
$parents = array('type', 'brand', 'car');
// you could also do:
// $path = "type][brand][car";
// $parents = explode("][", $path);
function GetCar($cars, $parents) {
foreach($parents as $key) {
$cars = $cars[$key];
// echo $key."<br>";
}
return $cars;
}
var_dump(GetCar($cars, $parents)); // OUTPUT: string(5) "Honda"
echo GetCar($cars, $parents); // OUTPUT: Honda
A snippet: https://3v4l.org/OKrQN
I still think, that there is a better solution for what you need in a bigger picture (that I don't know)
Here is the correct answer, I am not just saying that as I've done this many times before. And I have really analyzed the problem etc...
$array = array(
'type' => array(
'brand' => array(
'car' => 'Honda',
),
),
);
$path = "type][brand][car";
function transverseGet($path, array $array, $default=null){
$path = preg_split('/\]\[/', $path, -1, PREG_SPLIT_NO_EMPTY);
foreach($path as $key){
if(isset($array[$key])){
$array = $array[$key];
}else{
return $default;
}
}
return $array;
}
print_r(transverseGet($path, $array));
Output
Honda
Sandbox
The trick is, every time you find a key from the path in the array you reduce the array to that element.
if(isset($array[$key])){
$array = $array[$key];
At the end you just return whatever is left, because your out of path parts to run so you can assume its the one you want.
If it doesn't find that key then it returns $default, you can throw an error there if you want.
It's actually pretty simple to do, I have this same setup for set,get,isset - key transversal
Like a Ninja ()>==<{>============>
If you require to use that specific structure you could do something like this:
$path = "type][brand][car";
$path_elements = explode("][", $path);
This way you get an array with each of the components required, and you'll have to do something like:
echo $cars[$path_elements[0]][$path_elements[1]][$path_elements[2]];
Of course that is a little bit too static and needs the same 3 level element structure.
May be this can resolve the problem :
strong text$cars = array( 'type' => array(
'brand' => array(
'car' => 'Honda',
), ), );
$path = "type][brand][car";
preg_match_all('/[a-z]+/', $path,$res);
$re = $res[0];
echo $cars[$res[0][$res[1]][$res[2]];
Using this lib uploading works great. I have number of objects in an excel and I go through them and do whatever I desire.
The question is while uploading the excel I am ought to check whether a particular object already exists, if so increment the $rejected variable otherwise create and increment the $uploaded variable. As a result I would like to return the results: how many uploaded and how many rejected? Whats the best way to do as such? It is obvious I can't access those variables inside the function. What's the best practice here?
public function uploadUsingFile($file)
{
$rejected = 0;
$uploaded = 0;
Excel::load($file, function ($reader) {
foreach ($reader->toArray() as $row)
{
$plateAlreadyExist = Plate::where('serial_number', $row['plate_serial_number'])->exists();
if ($plateAlreadyExist) {
$rejected += 1;continue;
}
$supplier = Supplier::firstOrCreate(['name' => $row['supplier_name']]);
$statusName = EquipmentStatusCode::firstOrCreate(['name' => $row['status_name']]);
$plateType = PlateType::firstOrCreate(['name' => $row['plate_type_name']]);
$process = Process::firstOrCreate(['name' => $row['process_name']]);
$project = Project::firstOrCreate(['name' => $row['project_name']]);
$plateQuality = PlateQuality::firstOrCreate(['name' => $row['plate_quality']]);
$wafer = Wafer::firstOrCreate(['serial_number' => $row['wafer_serial_number']]);
$data = [
'serial_number' => $row['plate_serial_number'],
'crc_code' => $row['crc_code'],
'supplier_id' => $supplier['id'],
'equipment_status_code_id' => $statusName['id'],
'plate_type_id' => $plateType['id'],
'process_id' => $process['id'],
'project_id' => $project['id'],
'plate_quality_id' => $plateQuality['id'],
'wafer_id' => $wafer['id'],
'created_by' => Auth::user()->id,
];
if($data)
{
Plate::create($data);
$uploaded += 1;
}
}
});
return [ 'uploaded' => $uploaded, 'rejected' => $rejected ];
}
You can pass a reference to the variables into the closure by using the use keyword:
...
Excel::load($file, function ($reader) use(&$rejected, &$uploaded){
...
}
Anonymous Functions
How do I recursively get value from array where I need to explode a key?
I know, it's not good the question, let me explain.
I got an array
[
"abc" => "def",
"hij" => [
"klm" => "nop",
"qrs" => [
"tuv" => "wxy"
]
]
]
So, inside a function, I pass:
function xget($section) {
return $this->yarray["hij"][$section];
}
But when I want to get tuv value with this function, I want to make section as array, example:
To get hij.klm value (nop), I would do xget('klm'), but to get hij.klm.qrs.tuv, I can't do xget(['qrs', 'tuv']), because PHP consider $section as key, and does not recursively explode it. There's any way to do it without using some ifs and $section[$i] ?
function xget($section) {
return $this->yarray["hij"][$section];
}
that one is static function right?
you can do that also for this
function xget($section) {
if(isset($this->yarray["hij"][$section])){
return $this->yarray["hij"][$section];
}elseif(isset($this->yarray["hij"]["klm"]["qrs"][$section])){
return $this->yarray["hij"]["klm"]["qrs"][$section];
}
}
as long as the key name between two of them are not the same.
You could use array_walk_recursive to find tuv's value regardless of the nested structure:
$tuv_val='';
function find_tuv($k,$v)
{
global $tuv_val;
if ($k=='tuv')
$tuv_val=$v;
}
array_walk_recursive($this->yarray,"find_tuv");
echo "the value of 'tuv' is $tuv_val";
try my code
<?php
$array = array(
'aaa' => 'zxc',
'bbb' => 'asd',
'ccc' => array(
'ddd' => 'qwe',
'eee' => 'tyu',
'fff' => array(
'ggg' => 'uio',
'hhh' => 'hjk',
'iii' => 'bnm',
),
),
);
$find = '';
function xget($key){
$GLOBALS['find'] = $key;
$find = $key;
array_walk_recursive($GLOBALS['array'],'walkingRecursive');
}
function walkingRecursive($value, $key)
{
if ($key==$GLOBALS['find']){
echo $value;
}
}
xget('ggg');
?>
How do I convert from my PHP array (mysql_fetch_array) to a declared PHP Class then encode that to json format string. My array:
while ($rows = mysql_fetch_array($result, MYSQL_ASSOC)){
$patient[] = array( 'id' => $rows['id'],
'name' => $rows['name'],
'sex' => $rows['sex'],
'civil_status' => $rows['civil_status'],
'age' => $rows['age'],
'type_of_admission' => $rows['type_of_admission'],
'admission_diagnosis' => $rows['admission_diagnosis'],
'date_admitted' => $rows['date_admitted']);
}
My declare PHP Class
class Person
{
public $id;
public $name;
public $sex;
public $civil_status;
public $age;
public $type_of_admission;
public $admission_diagnosis;
public $date_admitted;
}
I think you are looking for mysql_fetch_object:
while ($row = mysql_fetch_object($result, 'Person')){
$json_rows[] = json_encode($row);
}
Also, you should be using mysqli, which has the same basic concept.
just retype to (object)
$object = (object) $array_name;
for json_encode.
i have a script but before that i want to explain u something
i an calling a function
$data['cat'] = $this->autoload_model->getTree(0,'td_category');
$data['cat'] = $this->autoload_model->getTree(0,'td_division');
so in the below function
$table = td_category
$table = td_division
public function getTree($pid,$table)
{
$table_data=explode("_",$table);
//$table_data[1] will read category for td_category, division for td_division;
global $sp;
static $arr = array(
'category_id' => array(),
'category_title' => array()
);
}
now if i replace this two lines
'category_id' => array(),
'category_title' => array()
by
$table_data[1].'_id' => array(),
$table_data[1].'_title' => array()
then i am getting error due to the static nature of the array,
but if i delete the static keyword, then it doesnt show any error
how can i keep the static keywod and also get the associative fields dynamicaly base on the $table sent
I am not sure very much but you can try following
static $arr = array();
$arr[$table_data[1].'_id'] = array();
$arr[$table_data[1].'_title'] = array();
You mean something like this?
${$table_data[1]."_title"} => array();