PHP dynamically load data into a multidimensional array to use in ajax - php

I'm currently trying to get my php ldap backend to parse the ldap array into a normal array with the following layout (this is to pass back to an ajax call to then output into a table underneath a live directory search):
--NA
--(dynamic row entry)
--name
--office address
--telephone number
--mail
I manage to get my code :
//NEW ARRAY FOR COLUMN AND ROW
$na = array( array( ));
//MAKES IT EASIER TO RUN THROUGH ARRAY
$barray = array( cn , physicaldeliveryofficename , telephonenumber , mail );
//GOES THROUGH EACH ENTRY OUTPUTTING THAT ROW
for ($row=0; $row<$entries['count']; $row++) {
echo '<br />';
$na[] = $row;
//ADD EACH COL TO ARRAY AND DATA INTO COL
for ($col=0; $col<5; $col++) {
$na[$row][] = $col;
$na[$row][$col] = $entries[$row][$barray[$col]][0];
echo $na[$row][$col] . ' ';
}
}
Working to get the first row of names to output, then the for loop continues and outputs the correct amount of rows (for the parameter I tested with anyway, checked with a series of echo statements).
Can anyone give me tips as to why my code isn't working, and how to improve the code. Lastly any more efficient pointers would help as I'm more used to java than PHP. (summer job want it doing in PHP though)
Thanks in advance,
Joe
EDIT - VAR_DUMP
array(18) { [0]=> array(5) { [0]=> string(14) "Steven Johnson" [1]=> string(7) "Heywood" [2]=> string(11) "01706694297" [3]=> string(29) "Steven.Johnson#yearsley.co.uk" [4]=> NULL } [1]=> int(0) [2]=> int(1) [3]=> int(2) [4]=> int(3) [5]=> int(4) [6]=> int(5) [7]=> int(6) [8]=> int(7) [9]=> int(8) [10]=> int(9) [11]=> int(10) [12]=> int(11) [13]=> int(12) [14]=> int(13) [15]=> int(14) [16]=> int(15) [17]=> int(16) }
**EDIT 2 - SOLUTION:
After Barbara's comment I output the var_dump above, this lead me to see that the problem at hand was that the array was being declared in numerous different instances which was affecting the end array. Since I was instantiating the first row as a single array, then instantiating it as a multidimensional array then finally adding the data into the array.
To solve the problem I simply removed the $na[] = $row and $na[$row][] = $col parts to correctly make the array. **

Related

PHP: Incorrect value after assignment

I have really no idea what's happening. The story:
I use PDO for a SELECT statement on a database.
$sql = "SELECT a,b,c,performance,points,compare
FROM normvalues
WHERE x=:x AND y=1 AND z=:z";
$stmt = $GLOBALS['PDO']->prepare($sql);
$stmt->bindParam(":x",$x);
$stmt->bindParam(":z",$z);
$stmt->execute();
$res=$stmt->fetchAll(PDO::FETCH_ASSOC);
So that's fine and it is working. When I var_dump the $res variable I get something like:
array(6) {
["a"]=> string(2) "44"
["b"]=> string(4) "1176"
["c"]=> string(4) "1166"
["performance"]=> string(4) "50.1"
["points"]=> string(1) "1"
["compare"]=> string(2) "-1"
}
[1]=>
array(6) {
["a"]=> string(2) "57"
["b"]=> string(4) "1176"
["c"]=> string(4) "1166"
["performance"]=> string(4) "47.7"
["points"]=> string(1) "2"
["compare"]=> string(2) "-1"
}
[2]=>
array(6) {
["a"]=> string(2) "70"
["b"]=> string(4) "1176"
["c"]=> string(4) "1166"
["performance"]=> string(4) "44.7"
["points"]=> string(1) "3"
["compare"]=> string(2) "-1"
}
...
That's also okay. But I have to sort the result another way. So I am doing:
foreach($res as $e){
$this->normTable[$e['a']][$e['points']]=$e['performance'];
$this->normTable[$e['a']]['compare']=$e['compare'];
}
And now I am completely lost. By assigning $e['performance'] I get wrong values. Actually this should be the performance values.
[1176]=>
array(4) {
[1]=> string(2) "50"
["compare"]=> string(2) "-1"
[2]=> string(2) "48"
[3]=> string(2) "45"
}
I already checked the values in the database and they are correct. By doing doubleval() I'd get the right values, but the problem is that not every value is a double but also integer or string. I also tried to typecast with (string) but it's the same result. I have no explanation.
Update:
It's a very big project and I just tried to minimize it as possible and to make my problem as clear as possible. But now I have figured out something new:
I do an 'echo()' of my first variable in the normTable during the loop:
foreach($res as $e){
$this->normTable[$e['a']][$e['points']]=$e['performance'];
echo "a:".$e['a']." pt: ".$e['points']." perf: ".$e['performance']."-".$this->normTable[1176][1]."\n";
$this->normTable[$e['a']]['compare']=$e['compare'];
}
and the value is changing from '50.1' to '50'. Still can't figure out the reason. Is there a size limitaion of arrays in PHP?
UPDATE 2 and a big SORRY!
As I said, it is a big project. So the table I read out, has some values for some attributes twice or more. Actually such a case should not happen. That's why the answer is simple: It became 50 because 50 was assigned. I'm so sorry for having waisted your time. But I totally excluded this case and since I am also coding in C, my first thought was: memory leak - clear case!
Thanks for your help.
Meh, I don't have 50 reputation; can't comment only answer.
If you replace a with be in your loop, you should get your expected result (given your data sample). I.e.:
foreach($res as $e){
$this->normTable[$e['b']][$e['points']]=$e['performance'];
$this->normTable[$e['b']]['compare']=$e['compare'];
}
But I'm not sure this really solves your problem. YMMV.

Having trouble getting a specific value in JSON/PHP

I am trying to pull one single piece of data from a json encoded string. I managed to get the string into php's jason format, but I dont understand how to display the exact data I want (confirmations) Every time I try to access any of the data it just gives me a bracket({) and no data. I know I'm doing something wrong with retreiving the data from the variable, but I can't pu tmy finger on it.
Here's the data I want to parse, could someone please show me how to access the confirmations value from within the array of data? Thanks.
( https://projectbuilder.info/link.php?ID=jsontest&CMD=page ) [easier to read]
Source Code:
<?PHP
$return = file_get_contents("https://api.chain.com/v2/bitcoin/transactions/76e6f17cb940745255e2b8439eea5dae945a b148f1fbba98a9fb99c9a5801320?api-key-id=ae7317a1cd4ff0d12e49a77bfd8b9dec");
var_dump(json_decode($return));
echo $return[0]["confirmations"]; //one of my many attempts to get the info, also tried without the leading zero, and different numbers. I understand arrays, I just dont understand how the json data is formatted inside the array.
?>
Output Copy(what do I do with $return to get it's confirmation value of 2896?):
object(stdClass)#1 (11) {
["hash"]=>
string(64) "76e6f17cb940745255e2b8439eea5dae945ab148f1fbba98a9fb99c9a5801320"
["block_hash"]=>
string(64) "00000000000000001646d024d4622a0e4a5c06299d7d776de041bc9c317be1f8"
["block_height"]=>
int(329486)
["block_time"]=>
string(20) "2014-11-11T02:10:21Z"
["chain_received_at"]=>
string(24) "2014-11-11T02:05:48.259Z"
["confirmations"]=>
int(2896)
["lock_time"]=>
int(0)
["inputs"]=>
array(2) {
[0]=>
object(stdClass)#2 (7) {
["transaction_hash"]=>
string(64) "76e6f17cb940745255e2b8439eea5dae945ab148f1fbba98a9fb99c9a5801320"
["output_hash"]=>
string(64) "4f7b6066396e422f1cabd60767093ec6fb4480b60f206c408ad50895541bc023"
["output_index"]=>
int(0)
["value"]=>
int(144475)
["addresses"]=>
array(1) {
[0]=>
string(34) "1HPvAS96JXYUuLDs5CKNh61SvH6NJT1ykH"
}
["script_signature"]=>
string(213) "304602210087289ed01fd7d04e3c7eb5c38ea1944cbc3789658a1122610079a4f0421e2426022100fca6f5f4623bbac131f06ebdc7389ea0c76b4355da9508ecc7b02107385ee79d01 029a79a3cf6f8b90b7c1210e593a21e46c81ffbbe544eb2ab3ebbd89f33e4f8b2e"
["sequence"]=>
int(4294967295)
}
[1]=>
object(stdClass)#3 (7) {
["transaction_hash"]=>
string(64) "76e6f17cb940745255e2b8439eea5dae945ab148f1fbba98a9fb99c9a5801320"
["output_hash"]=>
string(64) "22de0dbb8d72fac9a6e8775f6f80fa3fc991c41d33fcd5081acb49c0479f2a62"
["output_index"]=>
int(1)
["value"]=>
int(7390022)
["addresses"]=>
array(1) {
[0]=>
string(34) "158kR5o6EWWhFEZfLqGDvkgfoyi2Ep2fhA"
}
["script_signature"]=>
string(209) "304402205e2f36c9c22e02767e3accc8bc609b74d5a23c58e4a8edbac24cb4baf1e3feaa022043ad33becd57c5dee03fd1c1d8be1524281f6f49ba1e44a1a2b340f89554c42d01 031181694e14973f71d45f5f3ab73ee0f30dfa3f488bf53c44e46cf9f4f3d3d722"
["sequence"]=>
int(4294967295)
}
}
["outputs"]=>
array(2) {
[0]=>
object(stdClass)#4 (9) {
["transaction_hash"]=>
string(64) "76e6f17cb940745255e2b8439eea5dae945ab148f1fbba98a9fb99c9a5801320"
["output_index"]=>
int(0)
["value"]=>
int(144475)
["addresses"]=>
array(1) {
[0]=>
string(34) "1P5rwnk3GYbxgpxN9M9EziLrpvoih4c8JC"
}
["script"]=>
string(85) "OP_DUP OP_HASH160 f23e1f6dd21bab989f18c14f26bf37b4e2372eef OP_EQUALVERIFY OP_CHECKSIG"
["script_hex"]=>
string(50) "76a914f23e1f6dd21bab989f18c14f26bf37b4e2372eef88ac"
["script_type"]=>
string(10) "pubkeyhash"
["required_signatures"]=>
int(1)
["spent"]=>
bool(false)
}
[1]=>
object(stdClass)#5 (9) {
["transaction_hash"]=>
string(64) "76e6f17cb940745255e2b8439eea5dae945ab148f1fbba98a9fb99c9a5801320"
["output_index"]=>
int(1)
["value"]=>
int(7380022)
["addresses"]=>
array(1) {
[0]=>
string(34) "1DpY5Mu2qTNkwsnPwgqFnaZ1Kq7GpKDboy"
}
["script"]=>
string(85) "OP_DUP OP_HASH160 8c9efff6e8500a36c16a939054a333d81ef23166 OP_EQUALVERIFY OP_CHECKSIG"
["script_hex"]=>
string(50) "76a9148c9efff6e8500a36c16a939054a333d81ef2316688ac"
["script_type"]=>
string(10) "pubkeyhash"
["required_signatures"]=>
int(1)
["spent"]=>
bool(true)
}
}
["fees"]=>
int(10000)
["amount"]=>
int(7524497)
}
{
Have a look at the docs: http://php.net/json_decode
Convert the json-string to a php-array and save it in a variable. Then use it like any other array to get values from it. Like this:
$return = file_get_contents('http://etc.com/');
$decoded_return = json_decode($return);
echo $decoded_return['confirmations']; //Make sure the key exists, obviously
So keep in mind that $return is a string. The json_decode function returns an array, so you have to save that array in a (new - preferably) variable to get values from it.

How to set a variable inside a PHP object

I want to update two variables in my the Woocommerce cart object. I can see the structure of the arrays in the object with:
echo 'Cart Dump: ' . var_dump($woocommerce->session->cart)
This returns:
array(1) { ["01822dd92bc31f60fdb64f0c3c5eb241"]=> array(9) { ["product_id"]=> int(616) ["variation_id"]=> string(0) "" ["variation"]=> string(0) "" ["quantity"]=> int(1) ["addons"]=> array(2) { [0]=> array(3) { ["name"]=> string(5) "Color" ["value"]=> string(13) "Black / Black" ["price"]=> string(0) "" } [1]=> array(3) { ["name"]=> string(8) "Warranty" ["value"]=> string(13) "12 Month Free" ["price"]=> string(0) "" } } ["line_total"]=> float(689) ["line_tax"]=> float(0) ["line_subtotal"]=> float(689) ["line_subtotal_tax"]=> float(0) } } Cart Dump:
I want to be able to set the variables "value" and "price" inside that object.
My next step has been to try to step into the next array and have tried
echo 'Cart Dump: ' . var_dump($woocommerce->session->cart[1])
but I think I am mixing object references with array ones here and I am getting NULL. I can appreciate that I would be better off creating a function for the object but I am not sure how to best approach that if I cannot even access the variable I want to set.
Many thanks in advance.
There are no objects here, it's just that the array key is the string 01822dd92bc31f60fdb64f0c3c5eb241 and not the integer 1.
So to get / set your value, you would use:
$woocommerce->session->cart["01822dd92bc31f60fdb64f0c3c5eb241"]["addons"][0]["value"]
etc.
Depending on your php version you would probably need a temporary variable to get to the first element of your array if you don't know the key:
$temp = reset($woocommerce->session->cart);
$value = $temp["addons"][0]["value"];
You can try this:
//search the key of the array
$cart = $woocommerce->session->cart;
//update values using the key of the array as key
$woocommerce->session->cart[key($cart)]['value'] = 'your value';
$woocommerce->session->cart[key($cart)]['price'] = 'your price';

php code - trying to loop array

I am noticing some strange behavior while looping through some data. I'm sure it's something simple, but I can't seem to be able to find the bug.
I have the following logic:
<?php
print 'dumping data : <BR>';
var_dump($portvlan);
print '<BR>';
print 'looping through data: <BR>';
foreach ($portvlan as $vlandetail){
echo 'Vlanid: '.$vlandetail['VlanId'].'<BR>';
echo 'Name: '.$vlandetail['Name'].'<BR>';
echo 'Mode: '.$vlandetail['Mode'].'<BR>';
}
?>
This is the output that I'm getting:
dumping data :
array(3) { ["VlanId"]=> string(2) "33" ["Name"]=> string(6) "USR_33" ["Mode"]=> string(6) "Access" }
looping through data:
Vlanid: 3
Name: 3
Mode: 3
Vlanid: U
Name: U
Mode: U
Vlanid: A
Name: A
Mode: A
What I was expecting was to see it print a row with 3 cells, with the following values:
33, USR_33, Access.
Can you tell me where I'm going wrong?
Thanks.
EDIT 1
This logic works fine when the $portvlan array has more than one entry.
For example, on another set of data, the var_dump gives this result:
array(6) { [0]=> array(3) { ["VlanId"]=> string(1) "1" ["Name"]=> string(1) "1" ["Mode"]=> string(5) "Trunk" } [1]=> array(3) { ["VlanId"]=> int(2) ["Name"]=> int(2) ["Mode"]=> string(5) "Trunk" } [2]=> array(3) { ["VlanId"]=> int(3) ["Name"]=> int(3) ["Mode"]=> string(5) "Trunk" } [3]=> array(3) { ["VlanId"]=> int(4) ["Name"]=> int(4) ["Mode"]=> string(5) "Trunk" } [4]=> array(3) { ["VlanId"]=> int(5) ["Name"]=> int(5) ["Mode"]=> string(5) "Trunk" } [5]=> array(3) { ["VlanId"]=> string(2) "33" ["Name"]=> string(2) "33" ["Mode"]=> string(5) "Trunk" } }
And the loop logic works fine.
$vlandetail will be populated with a different item from the array on every iteration of the loop. You shouldn't be treating $vlandetail as an array. Just use it directly.
To get the key name of the array entry, you have to change the loop structure to this:
foreach ($portvlan as $key => $vlandetail) {
echo $key . ': ' . $vlandetail . '<br>';
}
How you get your $portvlan?
If you can know is $portvlan is not an array of $vlandetail, you can simply do this,
$portvlan = array($portvlan);
// start loop
Or you can do this before you loop it, to make sure $portvlan is a numerical array formed by $vlandetail
$portvlan = (isset($portvlan[0]))?$portvlan:array($portvlan);
// start loop

Targeting specific group when creating a campaign with mailChimp API

I cannot seem to figure out how to send to a group in my list using mailChimp API
My code looks like this:
$conditions = array('field'=>'interests-1', 'op'=>'all', 'value'=>'myGroup');
$opts = array('match'=>'any', 'conditions'=>$conditions);
$retval = $api->campaignSegmentTest($listId, $opts);
But this yields bool(false). When fetched by
$retval = $api->listInterestGroupings($listId);
my list looks like this:
array(1) {
[0]=>
array(5) {
["id"]=>
int(1)
["name"]=>
string(10) "myList"
["form_field"]=>
string(5) "radio"
["display_order"]=>
string(1) "0"
["groups"]=>
array(5) {
[0]=>
array(4) {
["bit"]=>
string(1) "1"
["name"]=>
string(9) "myGroup"
["display_order"]=>
string(1) "1"
["subscribers"]=>
int(1)
}
[1]=>
array(4) {
["bit"]=>
string(1) "2"
["name"]=>
string(9) "myGroup_2"
["display_order"]=>
string(1) "2"
["subscribers"]=>
int(1)
}
}
}
}
I have looked in the API documentation and searched for the answer, but cannot seem to figure it out. Grateful for help!
Looks like you are using the PHP wrapper - the first thing to do, like the examples included with it do, is to check for any errors by looking at $api->errorCode before messing with the $retval.
When you do that I'm certain you will see an error telling you that you haven't passed a proper "conditions" parameter since it is an array of arrays, not an array.

Categories