SimpleXML storing data into array [duplicate] - php

This question already has answers here:
Forcing a SimpleXML Object to a string, regardless of context
(11 answers)
Closed 8 years ago.
I'm working on storing result of xml feed into database... I'm able to load file... but when I want to store data into array, it stores instead of value ([title] = 'Klapka 120mm';) this:
[title] => SimpleXMLElement Object ( [0] => Klapka 120mm )
Do you know, where might be problem?
Source code:
Here is part of one function:
$import_file = simplexml_load_file($this->input->post('import_url')); // load file from url
$affected_products = 0;
foreach($import_file->SHOPITEM as $product) {
$affected_products += $this->import_product($product);
}
Here is first part of function import_product:
public function import_product($product)
{
/* save product data into array */
$data = array(
'title' => $product->PRODUCT,
'content' => $product->DESCRIPTION,
'price' => $product->PRICE,
'price_vat' => $product->PRICE_VAT,
'ean' => $product->EAN,
'count' => $product->AVAILABILITY
);
die(print_r($data));
Thank you very much for your replies

You have to cast the elements to strings, as all these elements are instances of SimpleXMLElement.
$data = array(
'title' => (string)$product->PRODUCT,
'content' => (string)$product->DESCRIPTION,
'price' => (string)$product->PRICE,
'price_vat' => (string)$product->PRICE_VAT,
'ean' => (string)$product->EAN,
'count' => (string)$product->AVAILABILITY
);
For some of them a cast to an integer or a float may be of interest

Related

PHP - foreach loop not return all keys and values [duplicate]

This question already has answers here:
PHP Associative Array Duplicate Keys
(6 answers)
Closed 4 months ago.
I have an array in my php code
$list = array(
'RETAIL' => 'SUPERMARKET'
'RETAIL' => 'BAR'
'RETAIL' => 'DEP. MARKET'
'BUSINESS' => 'HOTEL'
'BUSINESS' => 'PUB'
'OTHER' => 'GROCERY'
'OTHER' => 'BUTCHERY'
// I have 20+ items
);
foreach( $list as $type => $name ){
var_dump($type,$name);
}
//var_dump() output
// RETAIL SUPERMARKET
// BUSINESS HOTEL
// OTHER BUTCHERY
I'm facing the problem that when I try to loop the array only three values will be returned and the rest are ignored. How I can fix this?
I'm trying to loop the array to save the data into a custom wordpress database. With the same way I've successfully looped another array inserted the keys and values into the db.
I think a better structure for your array would something like this
$list = [
'RETAIL' => [
'BAR',
'RESTAURANT'
]
];
And you could loop over like so
foreach ($list as $businessType => $businesses) {
foreach ($businesses as $business) {
echo "<li>{$business}</li>";
}
}
Just an example
As a general way of handling instances where you have more than one element to each piece of data (even when it's not in a tree structure like this may be), you should structure each item in the list as either an array or object, eg:
$list_of_arrays = [
['RETAIL', 'SUPERMARKET'],
['RETAIL', 'BAR'],
['RETAIL', 'DEP. MARKET'],
];
foreach( $list_of_arrays as $array ){
echo "<li>{$array[0]} {$array[1]}</li>";
}
or
$list_of_objects = [
(object)['type' => 'RETAIL', 'subtype' => 'SUPERMARKET'],
(object)['type' => 'RETAIL', 'subtype' => 'BAR'],
(object)['type' => 'RETAIL', 'subtype' => 'DEP. MARKET'],
];
foreach( $list_of_objects as $object ){
echo "<li>{$object->type} {$object->subtype}</li>";
}
Maybe I show heavily but as you only have two data for each entity, why your table is not built like this at the base...?
$list = array(
'SUPERMARKET'=>'RETAIL',
'BAR'=>'RETAIL',
'DEP. MARKET'=>'RETAIL',
'HOTEL'=>'BUSINESS',
'PUB'=>'BUSINESS',
'GROCERY'=>'OTHER',
'BUTCHERY'=>'OTHER'
// I have 20+ items
);
You do have keys that uniquely identify entities.

PHP - How do I add a name to an array

I am building an array (json encoded) and returning it to the caller. My output currently looks like this:
[{"org_id":1,"org_name":"Org 1"},{"org_id":4,"org_name":"Org 4"}]
I want to add a name so that output looks like this:
{
“orgs” : [
{"org_id":1,"org_name":"Org 1"},
{"org_id":4,"org_name":"Org 4"}
]
}
Here is my current code:
// if orgs were found then
if ( is_array($orgs) && !empty($orgs) ) {
$json_orgs = json_encode($user_orgs);
// else return an empty array
} else {
$user_orgs = array();
}
I am fairly new to OO coding, so I have not figured out how to initialize an object so that "orgs" is present. Maybe I don't even need an object. Any help would be greatly appreciated.
Before you json encode the array, just wrap it in another one:
$newArray = ['orgs' => $yourCurrentArray];
Then you json encode the new variable instead.
If you rather not create a new array, you can simply do:
json_encode(['orgs' => $yourCurrentArray]);
This doesn't really have anything to do with OOP since you're just working with arrays. Associative arrays becomes objects when encoded into JSON.
You didn't say exactly how you're generating the JSON at the moment, or from what object/variable in PHP, or with what structure (there is more than one possible way).
But in general, here's how you could do it with an associative array:
$data = array (
'orgs' =>
array (
0 =>
array (
'org_id' => 1,
'org_name' => 'Org 1',
),
1 =>
array (
'org_id' => 4,
'org_name' => 'Org 4',
),
),
)
And then json_encode that to get the JSON.
(Hint: you can simply do the process in reverse to generate this example code from the desired JSON.)
You can achieve this by adding a key, for example:
// variable holding your data
$data;
// return statement in your controller
return ['orgs' => $data];
You just need to decode this with json_decode() and then you get like this
array (
0 =>
array (
'org_id' => 1,
'org_name' => 'Org 1',
),
1 =>
array (
'org_id' => 4,
'org_name' => 'Org 4',
),
)
then you need to add parant array on it
array( "orgs"=> array (
0 =>
array (
'org_id' => 1,
'org_name' => 'Org 1',
),
1 =>
array (
'org_id' => 4,
'org_name' => 'Org 4',
),
)
)
then again encode it and you will get your answer

PHP put an if command in an array [duplicate]

This question already has answers here:
Using an If-else within an array
(10 answers)
Closed 4 years ago.
This is a bit of an odd one. I am building an array in PHP and then encoding it to JSON before I spit it out.
$arr = array (
'reportDescription' =>
array (
if ($queryType == "realtime")
{
'source' => 'realtime',
}
'reportSuiteID' => 'rbsglobretailprod',
'dateGranularity' => $queryGran,
'dateFrom' => $queryFrom,
'dateTo' => $queryTo,
'elements' =>
array (
0 =>
array (
'id' => $queryElement,
),
),
'metrics' =>
array (
0 =>
array (
'id' => $queryMetric,
),
),
),
);
I am trying to get it to add a line to the array if the query type is realtime. This is what I tried but I'm not sure if it's possible to do this, and if it's not, I'm not sure how I should approach it. The error I get below suggests it may not be possible:
Parse error: syntax error, unexpected 'if' (T_IF), expecting ')'
You should do it as two separate calls:
$array = ['your', 'array', 'with', 'fields']
if ($queryType === 'realtime') {
$array[] = ['source' => 'realtime'];
}
Obviously change out the values with your expected values, but that should do the job. You could also append like so if you wanted it at root level:
if ($queryType === 'realtime') {
$array['source'] = 'realtime';
}

PHP - Get the current array with string [duplicate]

This question already has answers here:
How to access array elements
(6 answers)
Closed 4 years ago.
$form = array(
array(
'form' => 'Change Schedule',
'data' => array(
array(
'element'=>'input',
'name'=>'form-start',
'class'=>'form-control',
'type'=>'text',
'column'=>'col-md-12',
'label'=>'Schedule'
)
),
),
array(
'form' => 'Maintenance',
'data' => array(
array(
'element'=>'input',
'name'=>'form-room-place',
'class'=>'form-control',
'type'=>'text',
'column'=>'col-md-12',
'label'=>'Room # / Place'
)
),
),
);
This is the array I made, I wanted to get the array with form = Maintenance only. Is this possible with php to get the array via string arrays I want to pass?
My attempt:
$form(('form'=>'Change Dormitory'));
You've got 2 arrays inside the first array, so the internal arrays are $form[0] or $form[1].
You could then do $form[1]["form"] to get "Maintenance"
if you want to get the array data inside form = "Maintenance",
you can filter by form value like this:
$newForm = array();
foreach ($form as $key => $value) {
if ($value['form'] == 'Maintenance') {
$arr[] = $value;
}
}
var_dump($newForm);

Array in functions Yii Framework

can someone tell me what is this code doing, As im new to Yii, learning about it.. im not able to understand few things.. Here is the code..
$allmsg = LogMsg::model()->findAll($criteria); //
$dataArr = array();
if (isset($allMsg) && sizeof($allMsg) != 0):
foreach ($allMsg as $msg) {
$dataArr[$msg->date][] = array( // array?
'category' => $msg->category, // what is that 'category' a variable or something else? and $msg->category, is what?
'time' => $msg->time,
'date' => $msg->date,
'user' => $msg->name
);
} endif;
$this->render('index', array(
'data' => $dataArr ) //what is that 'data'?
);
My question is, what is this line of code doing exactly in foreach loop
$dataArr[$msg->date][] = array(
'category' => $msg->category,
and here is second code... which has something like that..
$allCat = Categories::model()->findAll($criteria);
$catArr=array();
if(isset($allCat) && sizeof($allCat)!=0):
foreach ($allCat as $catModel) {
$catArr[$catModel->id] =$catModel;
}
endif;
return $catArr;
so what is this line doing in this code in foreach loop, what is different between these two lines in first and second code..
$catArr[$catModel->id] =$catModel;
last thing.. what is it
public static function getID($category)
{
$arr = array(
'ast'=>1, // what are these things? from where are they coming? db?
'fp'=>5, //
'per'=>3,
'ts'=>6,
'lg'=>3
);
return isset($arr[$category])?$arr[$category]:null; //Ternary - Condensed if/else statement
}
So as per your first question.
$dataArr[$msg->date][] = array(
'category' => $msg->category,
$allMsg is the active record object which u get through the db query. This object is traversed in a loop and each row is "$msg".
Hence you can access the attributes of the model through the $msg->category. 'category' here is the attribute of the model.
this is creating multidimensional array.
Your first question
$dataArr[$msg->date][] = array(
'category' => $msg->category,
will generate output like
[2016-03-04] => Array
(
[0] => Array
(
[category] => abc
)
)
And your second question
$catArr[$catModel->id] =$catModel;
will genrate output like
array(
[0] =>1,
[1] => 2,
[2] => 3,
)
Not tested.
I think, your question is not about Yii. You should read about arrays of PHP first. In the code multidimensional array have been used. It means that the array can contain another array as value.

Categories