php laravel foreach loop giving only 1 result from the array - php

what I want to do is to print the data with foreach, but whatever I have done, it prints the last element and not the other one,
where am i going wrong?
I want "PartyIdentification" to return up to each element.
I don't understand if I'm making a mistake in get and sets. Is there a short solution? I want to print more than one property.
the result of my output
i want to do
$aa = array(
0 => ['ID' => ['val' => '4000068418', 'attrs' => ['schemeID="VKN"']]],
1 => ['ID' => ['val' => '12345678901', 'attrs' => ['schemeID="TICARETSICILNO"']]],
2 => ['ID' => ['val' => '132546555', 'attrs' => ['schemeID="MERSISNO"']]]
);
$invoice_AccountSupplierParty_Party = new \Pvs\eFaturaUBL\Party();
$invoice_AccountSupplierParty_Party->PartyIdentification = InvoiceBuilder::getasd($aa);
public static function getasd(array $data)
{
$asd = new Olusturma();
$date = array();
foreach ($data as $datum) {
$asd->getID($data);
}
return $asd->getResult();
}
namespace App\Support\Invoice;
class Olusturma
{
public $contactDetails = array();
public function __construct()
{
$this->contactDetails = new \Erkan\eFaturaUBL\PartyIdentification();
}
public function setOlusturma(): Olusturma
{
return $this;
}
public function getID($data)
{
foreach ($data as $row => $innerArray) {
foreach ($innerArray as $innerRow => $value) {
$this->setID($value);
}
}
return $this;
}
public function setID($data): Olusturma
{
$this->contactDetails->ID = $data;
return $this;
}
public function getResult(): \Erkan\eFaturaUBL\PartyIdentification
{
return $this->contactDetails;
}

Related

Session Handler behaves like object

I want to force $_SESSION behave like object using custom session handler. Code as follows,
$_SESSION = [
'user' => [
'id' => '7',
'name' => 'James',
'lastname' => 'Bond',
'login' => '007',
'pass' => 'qwe7fyqw9mhev8qhr',
],
'kill' => [
'Mr_Muscle' => [
'status' => 'alive',
],
'Joe_Black' => [
'status' => 'dead',
]
],
];
$session = new Session();
echo $session->user->name;
$session->kill->Mr_muscle->status = 'dead';
$session->save();
I did it almost but I get warning:
Warning: Creating default object from empty value in /var/www/project/mvc/bootstrap.php on line 80
when I'm trying to create new value, in this case:
$session->kill->Dr_Quinn->status = 'dead';
Value will be created but I don't want to hide this warning, I want to do away with it.
class Session
{
public function __construct()
{
foreach ($_SESSION as $key => $value)
{
$this->{$key} = $value;
}
}
public function __set($name, $value)
{
$this->$name = $this->arrayToObject($value);
}
private function arrayToObject($array) {
if (!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = $this->arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
public function save()
{
$_SESSION = json_decode(json_encode(get_object_vars($this)), true);
}
How to fix it?
Just do
if (!isset($session->kill->Mr_muscle))
$session->kill->Mr_muscle = new stdClass();
$session->kill->Mr_muscle->status = 'dead';
to avoid this warning.

How to Call a function inside an array value using PHP

Actually I need to call a function inside an array value.
this my function
public function RelationName()
{
return $this->name .'--'. $this->relationship;
}
I need to call this above function in another function which present same class file
this is my another function:
public static function getClaimerNameList($cat_id, $subcat_id)
{
$out = [];
$emp_code = Employee::find()
->where(['importcompany_id' => $cat_id])
->andWhere(['id' => $subcat_id])
->all();
foreach ($emp_code as $dat => $datas) {
$out[] = ['id' => $datas['id'], 'name' => $datas['name'] ];
if($dat == 0){
$aux = $datas['id'];
}
($datas['id'] == $subcat_id) ? $selected = $subcat_id : $selected = $aux;
}
return $output = [
'output' => $out,
'selected' => $selected
];
}
Actually I need to call function here
foreach ($emp_code as $dat => $datas) {
$out[] = ['id' => $datas['id'], 'name' => $datas['name'] ];
}
instead 'name' => $datas['name'] of this, I need to call a function getRelationName()
without using function am getting output like
id name
1 raja
2 ram
but I don't wanna output like that, if I use a function I will get output like below
id name
1 raja-father
2 ram-son
Help me to sort out this problem
You need to call it like this
foreach ($emp_code as $dat => $datas)
{
$out[] = ['id' => $datas['id'], 'name' => $datas->RelationName() ];
//more code...
}
And RelationName() need to be located in the Employee class and it shouldn't be static

copy array to xml cant change xml tag titles

for example i have an array
Array ( [0] => car [1] => bmw [2] => colour [3] => red [4] => quality [5] => good)
i also have a class what copy array to xml.
it copy array to xml like this
<root>
<0>car</0>
<1>bmw</1>
<2>colour</2>
<3>red</3>
<4>quality</4>
<5>good</5>
</root>
i need to copy array to xml like this
<root>
<car>bmw</car>
<colour>red</colour>
<quality>good</quality>
</root>
my class
class Array2XML {
private $writer;
private $version = '1.0';
private $encoding = 'UTF-8';
private $rootName = 'root';
function __construct() {
$this->writer = new XMLWriter();
}
public function convert($data) {
$this->writer->openMemory();
$this->writer->startDocument($this->version, $this->encoding);
$this->writer->startElement($this->rootName);
if (is_array($data)) {
$this->getXML($data);
}
$this->writer->endElement();
return $this->writer->outputMemory();
}
public function setVersion($version) {
$this->version = $version;
}
public function setEncoding($encoding) {
$this->encoding = $encoding;
}
public function setRootName($rootName) {
$this->rootName = $rootName;
}
private function getXML($data) {
foreach ($data as $key => $val) {
if (is_numeric($key)) {
$key = 'key'.$key;
}
if (is_array($val)) {
$this->writer->startElement($key);
$this->getXML($val);
$this->writer->endElement();
}
else {
$this->writer->writeElement($key, $val);
}
}
}
}
In your convert($data) method, change the following part:
if (is_array($data)) {
$this->getXML($data);
}
To:
if(is_array($data))
{
if(count($data)%2===0)
{
$cache=array();
while(count($data)>0)
{
list($key,$val)=array_splice($data,0,2);
$cache[$key]=$val;
}
print_r($cache);//just to debug
$this->getXML($cache);
}
else
{
$this->getXML($data);
}
}
I didn't test your whole class, but for the manipulating part, I did tested:
$data=array("car","bmw","colour","red","quality","good");
if(count($data)%2===0)
/* ...... */
print_r($cache);
The above code outputs:
Array
(
[car] => bmw
[colour] => red
[quality] => good
)
You need to pair each two values to get the name and the value of the element to add. You can do that with array_chunk for example:
$data = Array(0 => 'car', 1 => 'bmw', 2 => 'colour', 3 => 'red', 4 => 'quality', 5 => 'good');
$count = count($data);
if ($count % 2) {
throw new InvalidArgumentException('Array not of pairs.');
}
$xml = new XMLWriter();
$xml->openMemory();
$xml->startDocument();
$xml->startElement('root');
foreach (array_chunk($data, 2) as $pair) {
list($name, $value) = $pair;
$xml->writeElement($name, $value);
}
$xml->endElement();
echo $xml->outputMemory();
As you're using memory anyway, you can do this with SimpleXML instead as well:
$data = Array(0 => 'car', 1 => 'bmw', 2 => 'colour', 3 => 'red', 4 => 'quality', 5 => 'good');
$count = count($data);
if ($count % 2) {
throw new InvalidArgumentException('Array not of pairs.');
}
$xml = new SimpleXMLElement('<root/>');
foreach (array_chunk($data, 2) as $pair) {
list($name, $value) = $pair;
$xml->{$name}[] = $value;
}
echo $xml->asXML(), "\n";

How to create nested object from nested arrays in php

I have code like this, that initialize config
$this->config = array(
'users' => array(
array('name' => 'admin',
'password' => $password
)
),
'tokens' => array(),
'sessions' => array(),
);
that I'm saving to a file using json_encode($this->config) and later I load it using
json_decode(file_get_contents('file.json'));
it create nested objects, I would like to have this nested object when I initialize and the config, is there a way to create this nested object other then this?
$this->config = json_decode(json_encode($this->config));
You can alternatively use this function
<?php
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
?>
I decide to use this function instead
function object($array) {
$object = new stdClass();
foreach ($array as $k => $v) {
$object->$k = $v;
}
return $object;
}
and explicitly call it for assoc arrays
$this->config = object(array(
'users' => array(
object(array(
'name' => 'admin',
'password' => $password
))
),
'tokens' => array(),
'sessions' => array(),
));
EDIT recursive code
function is_assoc($array) {
if (!is_array($array)) {
return false;
} else {
$keys = array_keys($array);
return !is_numeric($keys[0]);
}
}
function object($array) {
if (is_assoc($array)) {
$object = new stdClass();
foreach ($array as $k => $v) {
$object->$k = object($v);
}
return $object;
} else {
return $array;
}
}

How to modify output of certain function of File_CSV_DataSource?

The following function is from a PEAR script called File_CSV_DataSource, and is a CSV parser.
CSV file is this:
name,age,skill
john,13,knows magic
tanaka,8,makes sushi
jose,5,dances salsa
The current output of this function is like this:
array (0 => array ('name' => 'john','age' => '13','skill' => 'knows magic',),1 =>array('name' => 'tanaka','age' => '8','skill' => 'makes sushi',),2 =>array ('name' => 'jose','age' => '5','skill' => 'dances salsa',),)
what I'm trying to achieve is to make the function to output like this:
array (array ('john','13','knows magic'), array('tanaka','8','makes sushi'), array ( 'jose','5','dances salsa'),)
so without the 0 => and without the column header => , only the value of the cells
Is there any way for me to modify the function bellow to make it output as in my example above?
public function connect($columns = array())
{
if (!$this->isSymmetric()) {
return array();
}
if (!is_array($columns)) {
return array();
}
if ($columns === array()) {
$columns = $this->headers;
}
$ret_arr = array();
foreach ($this->rows as $record) {
$item_array = array();
foreach ($record as $column => $value) {
$header = $this->headers[$column];
if (in_array($header, $columns)) {
$item_array[$header] = $value;
}
}
// do not append empty results
if ($item_array !== array()) {
array_push($ret_arr, $item_array);
}
}
return $ret_arr;
}
Thanks in advance
Just use the built in filegetcsv. It will do that for you.

Categories