I have this code:
function factuur_get_cardetails($form, &$form_state) {
//dd('getting cardetails');
$commands = array();
$i = 0;
foreach ($form_state['values']['field_invoice_line_deukendokter']['und'] as $line) {
if (count($line) > 1) {
// car
//dd($line);
// veld uitlezen
$kenteken = $line['field_invoice_carlicensenumber']['und'][0]['value'];
//dd($kenteken);
$url = 'https://api.datamarket.azure.com/opendata.rdw/VRTG.Open.Data/v1/KENT_VRTG_O_DAT?$filter=Kenteken%20eq%20%27'."$kenteken".'%27';
$xml = simplexml_load_file($url);
foreach($xml->entry as $entry){
$properties = $entry->content->children('http://schemas.microsoft.com/ado/2007/08/dataservices/metadata');
$auto = $properties->properties->children('http://schemas.microsoft.com/ado/2007/08/dataservices');
dd($auto->Handelsbenaming[0]);
$model = 'field_invoice_line_deukendokter[und]['.$i.'][field_invoice_carmodel][und][0][value]';
$id = "input[name='".$model."']";
$commands[] = ajax_command_invoke($id, 'val', array($auto->Handelsbenaming));
}
}
$i+=1;
}
return array('#type' => 'ajax', '#commands' => $commands);
}
The problem is when its gives me back [Object object] in my textbox while using
$commands[] = ajax_command_invoke($id, 'val', array($auto->Handelsbenaming));
Tho when i make a log using dd($auto) i get this
SimpleXMLElement Object
(
[Brandstofverbruikbuitenweg] => 3.20
[Brandstofverbruikgecombineerd] => 3.60
[Brandstofverbruikstad] => 4.30
[Catalogusprijs] => 20916
[Cilinderinhoud] => 1560
[CO2uitstootgecombineerd] => 95
[Datumaanvangtenaamstelling] => 2011-07-19T00:00:00
[DatumeersteafgifteNederland] => 2011-07-19T00:00:00
[Datumeerstetoelating] => 2011-07-19T00:00:00
[Eerstekleur] => GRIJS
[G3installatie] => N.v.t.
[Handelsbenaming] => DS3
)
So it somehow doesn't give me the value in "Handelsbenaming" and i don't know why.
Does anyone have an idea?
When i make a log dd($auto->Handelsbenaming);
it gives me this
SimpleXMLElement Object
(
[0] => DS3
)
but in my textbox it says [Object object] instead of DS3
Related
For some reach my array returns the data numerous times, for different arrays after filtering via a foreach in the second example the post only contains 1 unique link so the rest shouldn't exist at all, it should print simply the data from image_1 here's the PHP code.
$imagecounter = 1;
foreach ($html2->find('.post img') as $source) {
$link = $source->src;
if (strpos($link, 'https://www.example.com/wp-content/uploads/') !== false) {
$data['image_'.$imagecounter++.''] = $link;
}
}
And here's the array.
Array
(
[url] => https://www.example.com/something-with-data/
[featured_image] => https://www.example.com/wp-content/uploads/2018/11/something-1.jpg
[name] => Main Categories
[image_1] => https://www.example.com/wp-content/uploads/2018/11/something-11.jpg
[image_2] => https://www.example.com/wp-content/uploads/2018/10/something-1.jpg
[image_3] => https://www.example.com/wp-content/uploads/2018/10/something-1.png
[image_4] => https://www.example.com/wp-content/uploads/2018/10/something-2.jpg
[image_5] => https://www.example.com/wp-content/uploads/2018/11/something-3.jpg
[image_6] => https://www.example.com/wp-content/uploads/2018/11/something-4.jpg
[image_7] => https://www.example.com/wp-content/uploads/2018/11/something-5.jpg
[image_8] => https://www.example.com/wp-content/uploads/2018/11/something-6.jpg
[image_9] => https://www.example.com/wp-content/uploads/2018/11/something-7.jpg
[image_10] => https://www.example.com/wp-content/uploads/2018/11/something-8.jpg
[image_11] => https://www.example.com/wp-content/uploads/2018/11/something-9.jpg
)
Array
(
[url] => https://www.example.com/a-completely-different-post
[featured_image] => https://www.example.com/wp-content/uploads/2018/10/UmekRLrlwK8.jpg
[name] => Main Categories
[image_1] => https://www.example.com/wp-content/uploads/2018/10/UmekRLrlwK8.jpg (THIS IS FROM THE NEW ITERATION)
[image_2] => https://www.example.com/wp-content/uploads/2018/10/something-1.jpg
[image_3] => https://www.example.com/wp-content/uploads/2018/10/something-1.png
[image_4] => https://www.example.com/wp-content/uploads/2018/10/something-2.jpg
[image_5] => https://www.example.com/wp-content/uploads/2018/10/something-3.jpg
[image_6] => https://www.example.com/wp-content/uploads/2018/10/something-4.jpg
[image_7] => https://www.example.com/wp-content/uploads/2018/10/something-5.jpg
[image_8] => https://www.example.com/wp-content/uploads/2018/10/something-6.jpg
[image_9] => https://www.example.com/wp-content/uploads/2018/10/something-7.jpg
[image_10] => https://www.example.com/wp-content/uploads/2018/10/something-8.jpg
[image_11] => https://www.example.com/wp-content/uploads/2018/10/something-9.jpg
[image_12] => https://www.example.com/wp-content/uploads/2018/10/something-10.jpg
)
Start with an empty $data array.
$data = [];
$imagecounter = 1;
foreach ($html2->find('.post img') as $source) {
$link = $source->src;
if (strpos($link, 'https://www.example.com/wp-content/uploads/') !== false) {
$data['image_'.$imagecounter++.''] = $link;
}
}
If you need to store multiple sets of $data, then you can store each new $data batch in a parent array.
foreach ($htmls as $html2) {
$data = [];
$imagecounter = 1;
foreach ($html2->find('.post img') as $source) {
$link = $source->src;
if (strpos($link, 'https://www.example.com/wp-content/uploads/') !== false) {
$data['image_'.$imagecounter++.''] = $link;
}
}
$result[] = $data;
}
i need to convert an xml to array.
I get the xml from an online api.
My code so far:
function download_page($path){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$path);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$retValue = curl_exec($ch);
curl_close($ch);
return $retValue;
}
$sXML = download_page('https://url/api/user/distgroup/domain/user?t=ticketofuser');
echo "xml start: ". htmlentities($sXML);
$oXML = new SimpleXMLElement($sXML);
echo "xml: ". $oXML;
foreach($oXML["distributionGroups"] as $key=>$value)
{
$groups[$key]["group"]["id"]=$value["id"];
$groups[$key]["group"]["domain"]=$value["domain"];
$groups[$key]["group"]["name"]=$value["name"];
$groups[$key]["group"]["type"]=$value["type"];
$groups[$key]["group"]["loggedIn"]=$value["loggedIn"];
$groups[$key]["group"]["nightMode"]=$value["nightMode"];
$groups[$key]["group"]["loggedInAgents"]=$value["loggedInAgents"];
$groups[$key]["group"]["freeAgents"]=$value["freeAgents"];
$groups[$key]["group"]["callsWaiting"]=$value["callsWaiting"];
}
$temp=array();
foreach ($groups as $key => $row) {
$temp[$key] = $row["id"];
}
array_multisort($temp, SORT_ASC, $groups);
$_SESSION["groups"]=$groups;
echo "groups: ". $groups;
Afterdownloaded the xml it looks like this when i echo it with htmlentities($sXML);
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<distributionGroups>
<group>
<id>33247</id>
<domain>soluno.se</domain>
<name>Kamoda Support</name>
<type>ATTENDANT</type>
<loggedIn>true</loggedIn>
<nightMode>false</nightMode>
<loggedInAgents>1</loggedInAgents>
<freeAgents>1</freeAgents>
<callsWaiting>0</callsWaiting>
</group>
<group>
<id>33257</id>
<domain>soluno.se</domain>
<name>Test 5</name>
<type>ATTENDANT</type>
<loggedIn>false</loggedIn>
<nightMode>false</nightMode>
<loggedInAgents>0</loggedInAgents>
<freeAgents>0</freeAgents>
<callsWaiting>0</callsWaiting>
</group>
</distributionGroups>
My problem is that my array is empty after my try to foreach fill the array.
What am i doing wrong?
In your second foreach, you are missing the key group. Also, you could use $oXML->group to iterator over the XML elements:
$oXML = new SimpleXMLElement($sXML);
$groups = [] ;
foreach($oXML->group as $group)
{
$groups[]["group"] = [
'id' => (string)$group->id,
'domain' => (string) $group->domain,
'name' => (string) $group->name,
'type' => (string) $group->type,
'loggedIn' => (string) $group->loggedIn,
'nightMode' => (string) $group->nightMode,
'loggedInAgents' => (string) $group->loggedInAgents,
'freeAgents' => (string) $group->freeAgents,
'callsWaiting' => (string) $group->callsWaiting,
];
}
$temp=array();
foreach ($groups as $key => $row) {
$temp[$key] = $row['group']["id"]; // missing 'group' in $row['group']
}
array_multisort($temp, SORT_ASC, $groups);
print_r($temp);
print_r($groups);
Output of $temp:
Array
(
[0] => 33247
[1] => 33257
)
Output of $groups:
Array
(
[0] => Array
(
[group] => Array
(
[id] => 33247
[domain] => soluno.se
[name] => Kamoda Support
[type] => ATTENDANT
[loggedIn] => true
[nightMode] => false
[loggedInAgents] => 1
[freeAgents] => 1
[callsWaiting] => 0
)
)
[1] => Array
(
[group] => Array
(
[id] => 33257
[domain] => soluno.se
[name] => Test 5
[type] => ATTENDANT
[loggedIn] => false
[nightMode] => false
[loggedInAgents] => 0
[freeAgents] => 0
[callsWaiting] => 0
)
)
)
Or you could remove "group" in your first array :
$oXML = new SimpleXMLElement($sXML);
$groups = [] ;
foreach($oXML->group as $group)
{
$groups[] = [
'id' => (string)$group->id,
'domain' => (string) $group->domain,
'name' => (string) $group->name,
'type' => (string) $group->type,
'loggedIn' => (string) $group->loggedIn,
'nightMode' => (string) $group->nightMode,
'loggedInAgents' => (string) $group->loggedInAgents,
'freeAgents' => (string) $group->freeAgents,
'callsWaiting' => (string) $group->callsWaiting,
];
}
$temp=array();
foreach ($groups as $key => $row) {
$temp[$key] = $row["id"];
}
array_multisort($temp, SORT_ASC, $groups);
You could make it more flexible by getting the code to copy across each element within the group, adding an element to the array with the element name. This means that as the XML changes (or if) then the code will still retain all of the data being passed over.
I've also merged the two loops, so that $temp is set in the same loop as the main data.
$oXML = new SimpleXMLElement($sXML);
$groups = array();
$temp=array();
foreach ( $oXML->group as $group ) {
$data = array();
foreach ( $group as $element ) {
$data[ $element->getName() ] = (string)$element;
}
$groups[]["group"] = $data;
$temp[] = $data["id"];
}
print_r($temp);
print_r($groups);
new SimpleXMLElement($sXML) creates an object (not an array) of an XML element. So in your case, this $oXML = new SimpleXMLElement($sXML); gives you the distributionGroups element. From there you can access its child elements like foreach($oXML->group as $group), but remember that $group would also be an instance of SimpleXMLElement(). To access the content of the element you actually need to cast the object, i.e. (int) $group->loggedInAgents, to get an integer value. Otherwise $group-> loggedInAgents will actually give you another SimpleXMLElement() object, rather than a variable.
read more in the docs
help me to convert the following array in to json.
I tried to convert the array.
Array
(
[0] => Array
(
[c_code] => 200001
[itemname] => 303 10CAP
[c_pack_code] => PK0075
[c_web_img_link] =>
)
[1] => Array
(
[c_code] => 200005
[itemname] => 3P 4TAB
[c_pack_code] =>
[c_web_img_link] =>
)
)
current result for the following code is
public function searchOrder($idx, $data) {
if (!empty($data)) {
$result = OrderbukModel::func_get_searchlist($idx,$data);
if (!empty($result)) {
$resultArray[] = $result;
print_r(json_encode($result));
} else {
$resultArray[$idx] = ["Mysql returns empty result !"];
print_r(json_encode($resultArray));
exit;
}
}
}
now i got the result is like
[{"c_code":"200001","itemname":"303 10CAP","c_pack_code":"PK0075","c_web_img_link":""},{"c_code":"200005","itemname":"3P 4TAB","c_pack_code":"","c_web_img_link":""}]
But I need the result as follows
[{"c_code":"2000001","c_code":"200005"},
{"itemname":"303 10CAP","itemname":"3P 4TAB"},
{"c_pack_code":"PK0075","c_pack_code":""},
{"c_web_img_link":"","c_web_img_link":""}]
Example of how you can you make the json from array. Collect the data in two different array and after loop marge them and store the result in another array after that encode them.
Note: Your desired JSON is not a valid format, you can't use same index
for two data.
Online Example: https://3v4l.org/kdPDI
$arr = array(
array(
'c_code' => '200001',
'itemname' => '303 10CAP',
'c_pack_code' => 'PK0075',
'c_web_img_link' => ''
),
array(
'c_code' => '200005',
'itemname' => '3P 4TAB',
'c_pack_code' => '',
'c_web_img_link' => ''
)
);
$res1 = array();
$res2 = array();
foreach($arr as $val){
$res1['c_code'][] = $val['c_code'];
$res1['itemname'][] = $val['itemname'];
$res2['c_pack_code'][] = $val['c_pack_code'];
$res2['c_web_img_link'][] = $val['c_web_img_link'];
}
$out = array(array_merge($res1, $res2));
echo json_encode($out);
How to get the first value of element of array in php.
My story board is like this:
I have an array like this:
(
[0] => Array
(
[ID] => 68
[MATERIAL] => I have
[AC] => Try
)
[1] => Array
(
[ID] => 69
[MATERIAL] => It
[AC] => No Surrender
)
)
I want to update some record on my database like this,
foreach element of array,
UPDATE MY TABEL SET MATERIAL = [MATERIAL], AC = [AC] where id= [id]
this is the model named m_admin :
public function update_eir_to_cost($id, $material, $ac) {
$data = array(
"MATERIAL" => $material,
"AC" => $ac);
$this->db->trans_start();
$this->db->where($id);
$this->db->update('tb_repair_detail', $data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
// generate an error... or use the log_message() function to log your error
echo "Error Updating";
} else {
echo "Alhamdulillah";
}
}
This is the controller :
public function update_json_detail() {
$post_data = $this->input->post("POST_ARRAY");
$execute = array();
foreach ($post_data as $data) {
$execute[] = array(
'ID'=> $data['0'],
'MATERIAL' => $data['7'],
'AC' => $data['8']
);
}
echo "<pre>";
print_r($execute); // return an array like above.
/*forech element
update table using model
*/
}
This will solve your problem:
public function update_json_detail() {
$post_data = $this->input->post("POST_ARRAY");
$execute = array();
foreach ($post_data as $data) {
$execute[] = array(
'ID'=> $data['0'],
'MATERIAL' => $data['7'],
'AC' => $data['8']
);
}
echo "<pre>";
print_r($execute); // return an array like above.
$this->load->model('m_admin');
foreach ($execute as $row) {
$this->m_admin->update_eir_to_cost($row['ID'], $row['MATERIAL'], $row['AC']);
}
}
I'm not even sure how to begin wording this question, but basically, I have an array, that looks like this:
Array
(
[0] => /
[1] => /404/
[2] => /abstracts/
[3] => /abstracts/edit/
[4] => /abstracts/review/
[5] => /abstracts/view/
[6] => /admin/
[7] => /admin/ads/
[8] => /admin/ads/clickcounter/
[9] => /admin/ads/delete/
[10] => /admin/ads/edit/
[11] => /admin/ads/list/
[12] => /admin/ads/new/
[13] => /admin/ads/sponsordelete/
[14] => /admin/ads/sponsoredit/
[15] => /admin/ads/sponsornew/
[16] => /admin/ads/stats/
[17] => /admin/boilerplates/
[18] => /admin/boilerplates/deleteboiler/
[19] => /admin/boilerplates/editboiler/
[20] => /admin/boilerplates/newboilerplate/
[21] => /admin/calendar/event/add/
[22] => /admin/calendar/event/copy/
)
And I need to 'reduce' / 'process' it into an array that looks like this:
Array
(
[''] => Array()
['404'] => Array()
['abstracts'] => Array
(
[''] => Array()
['edit'] => Array()
['review'] => Array()
['view'] => Array()
)
['admin'] => Array
(
['ads'] => Array
(
[''] => Array()
['clickcounter'] => Array()
['delete'] =>Array()
['edit'] => Array()
)
)
.....
.....
)
That, if manually initialized would look something like this:
$urlTree = array( '' => array(),
'404' => array(),
'abstracts'=> array( '' => array(),
'edit' => array(),
'review'=> array(),
'view' => array() ),
'admin' => array( 'ads'=> array( '' => array(),
'clickcounter'=> array(),
'delete' => array(),
'edit' => array() ) )
);
I usually stray away from asking straight up for a chunk of code on SO, but does anyone perhaps have any advice / code that can traverse my array and convert it to a hierarchy?
EDIT: Here is the bit I have right now, which, I know is pitifully small, I'm just blanking out today it seems.
function loadUrlData()
{
// hold the raw data, /blah/blah/
$urlData = array();
$res = sql::query( "SELECT DISTINCT(`url`) FROM `pages` ORDER BY `url` ASC" );
while( $row = sql::getarray( $res ) )
{
$urlData[] = explode( '/', substr( $row['url'], 1, -1 ) );
}
// populated, eventually, with the parent > child data
$treeData = array();
// a url
foreach( $urlData as $k=> $v )
{
// the url pieces
foreach( $v as $k2=> $v2 )
{
}
}
// $treeData eventually
return $urlData;
}
Looks rather easy. You want to loop through all lines (foreach), split them into parts (explode), loop through them (foreach) and categorize them.
Since you don't like asking for a chunk of code, I won't provide any.
Update
A very nice way to solve this is to reference the $urlTree (use &), loop through every part of the URL and keep updating a variable like $currentPosition to the current part in the URL tree. Because you use &, you can simply edit the array directly while still using a simple variable.
Update 2
This might work:
// a url
foreach( $urlData as $k=> $v )
{
$currentSection = &$treeData;
// the url pieces
foreach( $v as $k2=> $v2 )
{
if (!isset($currentSection[$v2])) {
$currentSection[$v2] = array();
}
$currentSection = &$currentSection[$v2];
}
}
I know you didn't ask for a chunk of code, but I'd just call this a petit serving:
$map = array();
foreach($urls as $url) {
$folders = explode('/', trim($url, '/'));
applyChain($map, $folders, array());
}
function applyChain(&$arr, $indexes, $value) { //Here's your recursion
if(!is_array($indexes)) {
return;
}
if(count($indexes) == 0) {
$arr = $value;
} else {
applyChain($arr[array_shift($indexes)], $indexes, $value);
}
}
It's fairly simple. We separate each url into its folders (removing trailing and leading slashes) and then work our way down the array chain until we reach the folder mentioned in the URL. Then we place a new empty array there and continue to the next URL.
My version:
$paths = array(
0 => '/',
1 => '/404/',
2 => '/abstracts/',
3 => '/abstracts/edit/',
4 => '/abstracts/review/',
5 => '/abstracts/view/',
6 => '/admin/',
7 => '/admin/ads/',
// ....
);
$tree = array();
foreach($paths as $path){
$tmp = &$tree;
$pathParts = explode('/', rtrim($path, '/'));
foreach($pathParts as $pathPart){
if(!array_key_exists($pathPart, $tmp)){
$tmp[$pathPart] = array();
}
$tmp = &$tmp[$pathPart];
}
}
echo json_encode($tree, JSON_PRETTY_PRINT);
https://ideone.com/So1HLm
http://ideone.com/S9pWw
$arr = array(
'/',
'/404/',
'/abstracts/',
'/abstracts/edit/',
'/abstracts/review/',
'/abstracts/view/',
'/admin/',
'/admin/ads/',
'/admin/ads/clickcounter/',
'/admin/ads/delete/',
'/admin/ads/edit/',
'/admin/ads/list/',
'/admin/ads/new/',
'/admin/ads/sponsordelete/',
'/admin/ads/sponsoredit/',
'/admin/ads/sponsornew/',
'/admin/ads/stats/',
'/admin/boilerplates/',
'/admin/boilerplates/deleteboiler/',
'/admin/boilerplates/editboiler/',
'/admin/boilerplates/newboilerplate/',
'/admin/calendar/event/add/',
'/admin/calendar/event/copy/');
$result = array();
foreach ($arr as $node) {
$result = magic($node, $result);
}
var_dump($result);
function magic($node, $tree)
{
$path = explode('/', rtrim($node, '/'));
$original =& $tree;
foreach ($path as $node) {
if (!array_key_exists($node, $tree)) {
$tree[$node] = array();
}
if ($node) {
$tree =& $tree[$node];
}
}
return $original;
}
<?php
$old_array = array("/", "/404/", "/abstracts/", "/abstracts/edit/", "/abstracts/review/", "/rrl/");
$new_array = array();
foreach($old_array as $woot) {
$segments = explode('/', $woot);
$current = &$new_array;
for($i=1; $i<sizeof($segments); $i++) {
if(!isset($current[$segments[$i]])){
$current[$segments[$i]] = array();
}
$current = &$current[$segments[$i]];
}
}
print_r($new_array);
?>
You might consider converting your text to a JSON string, then using json_decode() to generate the structure.