Add mysql row to existing array - php

I have an existing array, and I want to add some items in it from a mysql row
$extendedadmindetails = full_query("SELECT * FROM `tbladmins` WHERE `id`='{$_SESSION['adminid']}'");
$extendedadmindetailsrow = mysql_fetch_assoc ($extendedadmindetails);
array_push($apiresults, $extendedadmindetailsrow);
This returns an array in an array:
Array
(
[result] => success
[adminid] => 1
[name] => My Name
[notes] =>
[signature] =>
[allowedpermissions] => My Name
[departments] => 1
[requesttime] => 2017-02-26 12:44:06
[0] => Array
(
[id] => 1
[uuid] => sqdqsdqsdqsdq454
[roleid] => 1
[username] => Myname
[password] => $dfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdf
[passwordhash] => $jghjghjghjghjghjghjghjghjg
[updated_at] => 0000-00-00 00:00:00
)
)
while I need:
Array
(
[result] => success
[adminid] => 1
[name] => My Name
[notes] =>
[signature] =>
[allowedpermissions] => My Name
[departments] => 1
[requesttime] => 2017-02-26 12:44:06
[id] => 1
[uuid] => sqdqsdqsdqsdq454
[roleid] => 1
[username] => Myname
[password] => $dfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdf
[passwordhash] => $jghjghjghjghjghjghjghjghjg
[updated_at] => 0000-00-00 00:00:00
)
I believe I should use array_push to add to an existing array, but I'm not sure how to proceed from there. Do I need to loop trough the extendedadmindetailsrow array and add items 1 by 1?
Any one can help me out with this?
Thanks!!

use of array_merge is better in case
// Considering your mysql is returning only 1 row
foreach ($extendedadmindetailsrow as $key => $row) {
$arr = $row;
}
// after this if you will try array_push also that will work
$result = array_merge($apiresults, $arr);
print_r($result);

Take a look at array_merge
array_merge($apiresults, $extendedadmindetailsrow);

You can:
$result = $apiresults + $extendedadmindetailsrow;

Use array_merge()
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
Output will be
Array (
[0] => red
[1] => green
[2] => blue
[3] => yellow
)

Related

Parse XML to Array with SimpleXML

I've that xml structure retrieving from device
<packet>
<info action="fiscalmemory" fiscalmemorysize="1048576" recordsize="464" fiscal="1" uniqueno="ABC12345678" nip="123-456-78-90" maxrecordscount="2144" recordscount="7" maxreportscount="1830" reportscount="4" resetmaxcount="200" resetcount="0" taxratesprglimit="30" taxratesprg="1" currencychangeprglimit="4" currencychangeprg="0" fiscalstartdate="dd-mm-yyyy hh:dd:ss" fiscalstopdate="dd-mm-yyyy hh:dd:ss" currencyname="PLN" />
<ptu name="A" bres="Nobi">123.23</ptu>
<ptu name="B">123.23</ptu>
<ptu name="D">8</ptu>
<sale>999.23</sale>
</packet>
simpleXml does't see ptu's attributes
$array = simplexml_load_string($xml);
print_r($array);
It prints
SimpleXMLElement Object
(
[info] => SimpleXMLElement Object
(
[#attributes] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[ptu] => Array
(
[0] => 123.23
[1] => 123.23
[2] => 8
)
[sale] => 999.23
)
As we can see ptu doesn't contain attributes :/
I also tried parse it with recursive function because children also may contain chilren but without success :/
Could anybody point to me why SimpleXML doesn't take ptu's attributes and also share any parsing function?
Thanks in advance.
edited
As regards Nigel Ren I made that function
function parseXMLtoArray($xml){
$x = simplexml_load_string($xml);
$result = [];
function parse($xml, &$res){
$res['name'] = $xml->getName();
$res['value'] = $xml->__toString();
foreach ($xml->attributes() as $k => $v){
$res['attr'][$k] = $v->__toString();
}
foreach($xml->children() as $child){
parse($child, $res['children'][]);
}
}
parse($x, $result);
return $result;
}
$resArray = parseXMLtoArray($rawXml);
print_r($resArray);
this returns such array
Array
(
[name] => packet
[value] =>
[attr] => Array
(
[crc] => BKJFKHKD54
)
[children] => Array
(
[0] => Array
(
[name] => info
[value] =>
[attr] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[1] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => A
)
)
[2] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => B
)
)
[3] => Array
(
[name] => ptu
[value] => 8
[attr] => Array
(
[name] => D
)
)
[4] => Array
(
[name] => sale
[value] => 999.23
)
)
)
Is this correct?
Thanks again Nigel
When loading with SimpleXML, using print_r() gives only an idea of the content and doesn't have the full content. If you want to see the full content then use ->asXML()...
$array = simplexml_load_string($xml);
echo $array->asXML();
To check the attributes of <ptu> element, (this just gives the first one)...
echo $array->ptu[0]['name'];
This uses ->ptu to get the <ptu> element and takes the first one [0] and then takes the name attribute using ['name'].

Extract data from Array/Object in PHP?

First off, I'm new to PHP and coding in general, so this might be quite an obvious answer.
I'm currently working with the Strava API, and I'm trying to extract data from an Array/Object which is the result of the following API call:
$recentactivities = $api->get('athlete/activities', array('per_page' => 100));
which returns:
Array (
[1] => stdClass Object (
[id] => XXXX
[resource_state] => 2
[external_id] => XXXX
[upload_id] => XXXX
[athlete] => stdClass Object (
[id] => XXXX
[resource_state] => 1
)
[name] => Let\'s see if I can remember how to do this cycling malarkey...
[distance] => 11858.3
[moving_time] => 1812
[elapsed_time] => 2220
[total_elevation_gain] => 44
[type] => Ride
[start_date] => 2014-07-12T13:48:17Z
[start_date_local] => 2014-07-12T14:48:17Z
[timezone] => (
GMT+00:00
) Europe/London
[start_latlng] => Array (
[0] => XXXX
[1] => XXXX
)
[end_latlng] => Array (
[0] => XXXX
[1] => -XXXX
)
[location_city] => XXXX
[location_state] => England
[location_country] => United Kingdom
[start_latitude] => XXXX
[start_longitude] => XXXXX
[achievement_count] => 4
[kudos_count] => 1
[comment_count] => 0
[athlete_count] => 1
[photo_count] => 0
[map] => stdClass Object (
[id] => a164894160
[summary_polyline] => XXXX
[resource_state] => 2
)
[trainer] =>
[commute] =>
[manual] =>
[private] =>
[flagged] =>
[gear_id] => b739244
[average_speed] => 6.544
[max_speed] => 10.8
[average_cadence] => 55.2
[average_temp] => 29
[average_watts] => 99.3
[kilojoules] => 179.9
[device_watts] =>
[average_heartrate] => 191.2
[max_heartrate] => 200
[truncated] =>
[has_kudoed] =>
)
This repeats for the most recent activities.
I'm attempting to extract average_heartrate, which I can do for a single object using the following:
$recentactivities[1]->average_heartrate;
but I'd like to extract all instances of average_heartrate from the Array. I've tried to use a foreach statement, but to be honest, I have no idea where to start.
Any help would be much appreciated.
It's actually pretty simple you can indeed use a foreach loop:
foreach($myArray as $obj){
//$obj is an object so:
if(isset($obj->average_heartrate)){
echo $obj->average_heartrate;
}
}
With this code you iterate through your array with objects and save the wanted array within an array so you can work further with it.
$heartrateArray = array(); // create a new array
//iterate through it with an foreach
foreach($recentactivities as $activity){
// save the average_heartrate as a value under a new key in the array
$heartrateArray[] = $activity->average_heartrate;
}

PHP output an Array

i`ve an array with more arrays inside.
But how can i get a specific value from it ?
For example how can i output the first name "John" ?
I tried this but it doesn't work.
foreach($arr as $result) {
echo $result['CLIENTS']['FIRSTNAME'];
}
This is the < pre> output of the array
Array
(
[WHMCSAPI] => Array
(
[ACTION] => getclients
[RESULT] => success
[TOTALRESULTS] => 12
[STARTNUMBER] => 0
[NUMRETURNED] => 12
[CLIENTS] => Array
(
[CLIENT] => Array
(
[ID] => 14
[FIRSTNAME] => John
[LASTNAME] => Doe
[COMPANYNAME] => Muster Company
[EMAIL] => info#mustermann.de
[DATECREATED] => 2014-04-13
[GROUPID] => 0
[STATUS] => Active
)
)
)
)
The other answers & comments are almost right, but they didn't notice that you're iterating over the array.
Here's your code:
foreach($arr as $result) {
echo $result['CLIENTS']['FIRSTNAME'];
}
Inside the loop (this is important), $result is equal to:
Array
(
[ACTION] => getclients
[RESULT] => success
[TOTALRESULTS] => 12
[STARTNUMBER] => 0
[NUMRETURNED] => 12
[CLIENTS] => Array
(
[CLIENT] => Array
(
...
So to access the client name inside the loop, use this:
$firstname = $result["CLIENTS"]["CLIENT"]["FIRSTNAME"];
You're missing a couple levels of the array. Try $result['WHMCSAPI']['CLIENTS']['CLIENT']['FIRSTNAME'].

Change array index of mysql query result set

This is mymysql table
id name ssn phone email**
1 Asok 5466 9865893265 asok#gmail.com
2 Sokan 7856 9562358965 sakan#gmail.com
......
.....
when I am using select query, i will get result as:
Array ( [0] => Array ( [id] => 1 [name] => Asok [sin] => 5466 [phone] => 9865893265 [email] => asok#gmail.com ) [1] => Array ( [id] => 2 [name] => Sokan [sin] => 7856 [phone] => 9562358965 [email] => sakan#gmail.com ) ...)`
I need to get this result as
Array ( [5466] => Array ( [id] => 1 [name] => Asok [sin] => 5466 [phone] => 9865893265 [email] => asok#gmail.com )
[7856] => Array ( [id] => 2 [name] => Sokan [sin] => 7856 [phone] => 9562358965 [email] => sakan#gmail.com ) ...)
using sql query
Here the index 5466 and 7856 are the field 'ssn' (this is a unique no to that person)
Do you want like this?
SQL column name ssn, result array index sin. I wrote as sin
$newArray = array();
foreach ($results as $row)
{
$newArray[$row['sin']] = $row;
}
Look https://github.com/EllisLab/CodeIgniter/pull/429
this link same is being discussed
functions map_array($key_field, $value_field) and map($key_field, $value_field)
that return a map (dictionary) from the result set
Try mySQL Index Hint Syntax
index hint syntax

how to get individual values from this array

I got this result when I printed the array print_r($post);
Array ( [0] => Array ( [0] => stdClass Object ( [subscriber_id] => 80010055 [cto_id] => [name] => n [mobile] => 1234564444 [state] => [city] => fsd [cto_subscriber_id] => 0 [password] => e10adc3949ba59abbe56e057f20f883e [email] => n#n.com [email_verified] => 1 [ip_address] => ::1 [last_login_time] => 2012-10-24 11:37:19 ) ) [1] => Array ( [0] => stdClass Object ( [subscriber_id] => 80010055 [ip_address] => [landline_number] => [sex] => 0 [dob] => 0000-00-00 00:00:00 [marital_status] => hfg [state] => [addres] => fgh [city] => fghfg [pincode] => fghfgh ) ) )
How can I get single values
Typecast it to array?
$arr = (array)$post[0][0];
And then you'll be able to loop through it as through normal array
foreach ($arr as $key => $value){....}
foreach $post as $sub {
foreach $sub as $single {
echo $single;
}
}
Think you should learn the basics of arrays and objects first.
Anyway in order to get the value of lets say subscriber_id you should use the following:
$post[0][0]->subscriber_id
First you get into the array and then get the value out of the Object

Categories