copy dynamic value to array in php - php

Can we copy all the dynamic values to array for eg:
I have a function like this
<?php
$list_a = array(); //defining an array
$list_b = array();
$list_c = array();
addText($a,$b,$c)
{
$list_a[] = $a;
$list_b[] = $b;
$list_c[] = $c;
}
I will pass different values to addText() function after that I have to access those inserted value using foreach from another function.
How can we do that .

Just define your php variable as global.
Eg. global $list_a,$list_b,$list_c;
When you are using that variable in any function then first declare above variables in that function.
Eg:
addText($a,$b,$c)
{
global $list_a,$list_b,$list_c;
$list_a[] = $a;
$list_b[] = $b;
$list_c[] = $c;
}

To accomplish this you have to use concept of global variable
Try this:
$list_a = array(); //defining an array
$list_b = array();
$list_c = array();
function addText($a,$b,$c)
{
global $list_a, $list_b, $list_c;
array_push($list_a,$a);
array_push($list_b,$b);
array_push($list_c,$c);
}
addText('12','23',12);
echo '<pre>';
print_r($list_a);
print_r($list_b);
print_r($list_c);

This would work but it is bad design. See here why.
<?php
$list_a = array(); //defining an array
$list_b = array();
$list_c = array();
function addText($a,$b,$c)
{
global $list_a, $list_b, $list_c;
$list_a[] = $a;
$list_b[] = $b;
$list_c[] = $c;
}
function foreachThem()
{
global $list_a, $list_b, $list_c;
foreach($list_a as $item)
{
//...
}
foreach($list_b as $item)
{
//...
}
foreach($list_c as $item)
{
//...
}
}
A better way would be saving them in a parent array (this is optional but it reduces the amount of parameters and therefor the amount of code) and passing it as reference. See here for info on passing by reference.
<?php
$theLists = array(
"a" => array(),
"b" => array(),
"c" => array()
);
// note the '&'
function addText(&$lists, $a,$b,$c)
{
$lists["a"][] = $a;
$lists["b"][] = $b;
$lists["c"][] = $c;
}
// '&' is not needed here
function foreachThem($lists)
{
foreach($lists["a"] as $item)
{
//...
}
foreach($lists["b"] as $item)
{
//...
}
foreach($lists["c"] as $item)
{
//...
}
}

Try this,
<?php
$list_a = array(); //defining an array
$list_b = array();
$list_c = array();
addText($a,$b,$c)
{
$list_a[] = $a;
$list_b[] = $b;
$list_c[] = $c;
}
public function 'function_name'($list_a, $list_b, $list_c) {
foreach ($list_a as $list) {
echo $list;
}
}

Related

How looks good structure of construct for creating multidimensial array

I am trying to create constructor which creates an multidimensional array. My result should be like this:-
Checkout my array $result_array
For now I have error: Illegal offset type. Note that I have als use __toString() becose I work on xml data.
class Property {
public $xmlClass;
public $elemClass = '';
public $first_array = array();
public $result_array = array();
public $data = '';
public $data2 = '';
public function __construct($xml, $elem) {
$this->xmlClass = $xml;
$this->elemClass = $elem;
foreach ($xml->xpath('//*[#baza]') as $val) {
$this->first_array[] = $val;
foreach ($val->ksiazka as $value) {
$data = $value->$elem->__toString();
$this->result_array[$this->first_array][] = $data;
}
}
}
public function getResult() {
return $this->result_array;
}
}
$result_autor = new Property($xml, 'autor');
$autor = $result_autor->getResult();
You need to change your two foreach() like below:-
foreach($xml->xpath('//*[#baza]') as $val) {
//$this->first_array[] = $val; not needed
foreach($val->ksiazka as $key=> $value){ //check $key here
$data = $value->$elem->__toString();
$this->result_array[$key][] = $data; // add $key hear
}
}
If the above not worked then check this too:-
foreach($xml->xpath('//*[#baza]') as $key=> $val) { //check $key here
//$this->first_array[] = $val; not needed
foreach($val->ksiazka as $value){
$data = $value->$elem->__toString();
$this->result_array[$key][] = $data; // add $key hear
}
}

PHP - Create a multidimensional array using dynamic functions arguments

I need a function like this one:
function multi(){
$args = get_func_args();
$array = ????
return $array;
}
print_r(multi('foo','bar','baz',123));
// expected result: array([foo] => array([bar] => array([baz] => 123)))
I've answered multiple variations of this using a reference to build-up the array:
function multi() {
$path = func_get_args(); //get args
$value = array_pop($path); //get last arg for value
$result = array(); //define our result
$temp = &$result; //reference our result
//loop through args to create key
foreach($path as $key) {
//assign array as reference to and create new inner array
$temp =& $temp[$key];
}
$temp = $value; //set the value
return $result;
}
print_r(multi('foo','bar','baz',123));
This will also work:
function multi(){
$array = null;
$args = func_get_args();
while(count($args)>0) {
$last = array_pop($args);
$array = $array ? array($last=>$array) : $last;
}
return $array;
}
$data = multi('foo','bar','baz',123);
to update an existing value (no checks if items really exists)
function set_multi($val, &$target){
$args = array_slice(func_get_args(), 2);
while(count($args)>0) {
$first = array_shift($args);
$target = &$target[$first];
}
$target = $val;
}
set_multi(456, $data, 'foo', 'bar', 'baz');

Php: Array returning empty

I am stumped on my array is not being saved after having values added to it in the functions. I believe it is a problem with the variables not being in the scope of the function. I have the following variables:
$oldInterestIdArray = array();
$newInterestsIdArray = array();
and I have some functions to populate the arrays:
function oldInterestIds($value, $key)
{
$data = fetchInterestDetail($value);
$id = $data['id'];
$oldInterestIdArray[] = $id;
}
function getNewInterestIds($value,$key)
{
if(interestExists($value))
{
$data = fetchInterestDetail($value);
$id = $data['id'];
$newInterestsIdArray[] = $id;
}
else
{
addInterest($value);
$data = fetchInterestDetail($value);
$id = $data['id'];
$newInterestsIdArray[] = $id;
}
}
if(count($errors) == 0)
{
$newInterests = array_diff($interestsArray, $interests);
$common = array_intersect($interestsArray, $interests);
$toChangeId = array_diff($interests, $common);
array_walk($toChangeId, "oldInterestIds");
array_walk($newInterests, "getNewInterestIds");
echo json_encode($oldInterestIdArray);
}
}
But the $oldInterestIdArray is returning blank. But if I were to echo json inside the oldInterestIds function it works, which leaves me to believe this is a problem with the variables scope. I have tried changing the variable to:
global $oldInterestIdArray;
global $newInterestsIdArray;
But that is returning null. Any suggestions?
declare global $oldInterestIdArray; inside the function like
function oldInterestIds($value, $key)
{
global $oldInterestIdArray; // set here global;
$data = fetchInterestDetail($value);
$id = $data['id'];
$oldInterestIdArray[] = $id;
}
See Example
Pass your array in as a reference :
function oldInterestIds(&$arr, $value, $key)
{
$data = fetchInterestDetail($value);
$id = $data['id'];
$arr[] = $id;
}

Echo a value from an array based on function parameters

I need to be able to echo a value from a private property in one of my classes if a method is called within the class. It's a little tricky to explain so let me demostrate and hopefully someone can fill in the blank for me :)
<?php
class test {
private $array['teachers']['classes'][23] = "John";
public function __construct($required_array) {
$this->array['teachers']['classes'][23] = "John";
$this->array['students'][444] = "Mary";
$this->echo_array($required_array);
}
public function echo_array($array) {
// Echo the value from the private $this->array;
// remembering that the array I pass can have either
// 1 - 1000 possible array values which needs to be
// appended to the search.
}
}
// Getting the teacher:
$test = new test(array('teachers','classes',23));
// Getting the student:
$test = new test(array('students',444));
?>
Is this possible?
$tmp = $this->array;
foreach ($array as $key) {
$tmp = $tmp[$key];
}
// $tmp === 'John'
return $tmp; // never echo values but only return them
An other approach to get value;
class Foo {
private $error = false,
$stack = array(
'teachers' => array(
'classes' => array(
23 => 'John',
24 => 'Jack',
)
)
);
public function getValue() {
$query = func_get_args();
$stack = $this->stack;
$result = null;
foreach ($query as $i) {
if (!isset($stack[$i])) {
$result = null;
break;
}
$stack = $stack[$i];
$result = $stack;
}
if (null !== $result) {
return $result;
}
// Optional
// trigger_error("$teacher -> $class -> $number not found `test` class", E_USER_NOTICE);
// or
$this->error = true;
}
public function isError() {
return $this->error;
}
}
$foo = new Foo();
$val = $foo->getValue('teachers', 'classes', 24); // Jack
// $val = $foo->getValue('teachers', 'classes'); // array: John, Jack
// $val = $foo->getValue('teachers', 'classes', 25); // error
if (!$foo->isError()) {
print_r($val);
} else {
print 'Value not found!';
}

Split an array into sub arrays

I would like to split an array:
$o = json_decode('[{"id":"1","color":"green"},{"id":"2","color":"green"},{"id":"3","color":"yellow"},{"id":"4","color":"green"}]');
based on the color attribute of each item, and fill corresponding sub arrays
$a = array("green", "yellow", "blue");
function isGreen($var){
return($var->color == "green");
}
$greens = array_filter($o, "isGreen");
$yellows = array_filter($o, "isYellow");
// and all possible categories in $a..
my $a has a length > 20, and could increase more, so I need a general way instead of writing functions by hand
There doesn't seem to exist a function array_split to generate all filtered arrays
or else I need a sort of lambda function maybe
You could do something like:
$o = json_decode('[{"id":"1","color":"green"},{"id":"2","color":"green"},{"id":"3","color":"yellow"},{"id":"4","color":"green"}]');
$greens = array_filter($o, function($item) {
if ($item->color == 'green') {
return true;
}
return false;
});
Or if you want to create something really generic you could do something like the following:
function filterArray($array, $type, $value)
{
$result = array();
foreach($array as $item) {
if ($item->{$type} == $value) {
$result[] = $item;
}
}
return $result;
}
$o = json_decode('[{"id":"1","color":"green"},{"id":"2","color":"green"},{"id":"3","color":"yellow"},{"id":"4","color":"green"}]');
$greens = filterArray($o, 'color', 'green');
$yellows = filterArray($o, 'color', 'yellow');
In my second example you could just pass the array and tell the function what to filter (e.g. color or some other future property) on based on what value.
Note that I have not done any error checking whether properties really exist
I would not go down the road of creating a ton of functions, manually or dynamically.
Here's my idea, and the design could be modified so filters are chainable:
<?php
class ItemsFilter
{
protected $items = array();
public function __construct($items) {
$this->items = $items;
}
public function byColor($color)
{
$items = array();
foreach ($this->items as $item) {
// I don't like this: I would prefer each item was an object and had getColor()
if (empty($item->color) || $item->color != $color)
continue;
$items[] = $item;
}
return $items;
}
}
$items = json_decode('[{"id":"1","color":"green"},{"id":"2","color":"green"},{"id":"3","color":"yellow"},{"id":"4","color":"green"}]');
$filter = new ItemsFilter($items);
$greens = $filter->byColor('green');
echo '<pre>';
print_r($greens);
echo '</pre>';
If you need more arguments you could use this function:
function splitArray($array, $params) {
$result = array();
foreach ($array as $item) {
$status = true;
foreach ($params as $key => $value) {
if ($item[$key] != $value) {
$status = false;
continue;
}
}
if ($status == true) {
$result[] = $item;
}
}
return $result;
}
$greensAndID1 = splitArray($o, array('color' => 'green', 'id' => 1));

Categories