PHP foreach subarray in array - php

I'm trying to parse an array that looks like this:
array(1) {
["StrategischeDoelstellingenPerDepartement"] => array(412) {
[0] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "1"
["Nummer"] => string(2) "27"
["Titel"] => string(22) "DSD 01 - HULPVERLENING"
["IdBudgetronde"] => string(1) "2"
}
[1] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "2"
["Nummer"] => string(2) "28"
["Titel"] => string(24) "DSD 02 - Dienstverlening"
["IdBudgetronde"] => string(1) "2"
}
[2] => array(5) {
["CodeDepartement"] => string(8) "DEPBRAND"
["NummerHoofdstrategischeDoelstelling"] => string(1) "2"
["Nummer"] => string(2) "29"
["Titel"] => string(16) "DSD 03 - KLANTEN"
["IdBudgetronde"] => string(1) "2"
}
...
(The array goes on but it's too big to post it here in its entirety)
I can do a foreach loop on the array like this:
foreach($my_arr->StrategischeDoelstellingenPerDepartement as $row){
echo "i found one <br>";
}
However, I want to do the same thing on other arrays and I want to make the function generic. The first key (StrategischeDoelstellingenPerDepartement in this case) can sometimes change, which is why I'd like to do it generically. I've already tried the following:
foreach($my_arr[0] as $row){
echo "i found one <br>";
}
But then I get the following notice, and no data:
Notice: Undefined offset: 0 in C:\Users\Thomas\Documents\GitHub\Backstage\application\controllers\AdminController.php on line 29
This is probably a silly question, but I'm new to PHP and this seemed like the right way to do it. Obviously, it isn't. Can anyone help me out, please?

Use reset to grab the first element of $my_arr without knowing the key name:
$a = reset($my_arr);
foreach($a as $row){
echo "i found one <br>";
}

Shift the sub-array off the main array and loop over it:
$sub = array_shift($my_arr);
foreach ($sub as $row) {
echo $row['Titel'], "<br>";
}

You are trying to do is object, not array $my_arr->StrategischeDoelstellingenPerDepartement.
You could use isset() to check the index existence:
if(isset($my_arr['StrategischeDoelstellingenPerDepartement'])){
foreach($my_arr['StrategischeDoelstellingenPerDepartement'] as $row){
echo "i found one <br>";
}
}
Or, you could use array_values() to ignore the array keys and to make it an index array:
$my_new_arr = array_values($my_arr);
foreach($my_new_arr as $row){
echo "i found one <br>";
}

Use current ref : http://in3.php.net/manual/en/function.current.php
$a = current($my_arr);
foreach($a as $row){
echo "i found one <br>";
}

Related

PHP suppress part of array if duplicate

I have an array of database objects and I'm using foreach() to present the names and projects. Good, now the customer doesn't want duplicate names for when one person has multiple projects. This has to do with variable scope and this is my failed attempt to pull this stunt off. Here's a partial var_dump of the array of objects.
array [
0 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "Bone density scanner analysis"
}
1 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "analysis of foot"
}
]
What I want to end up with is:
array [
0 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "Bone density scanner analysis"
}
1 => {
["lastName"]=>
string(1) ""
["projectName"]=>
string(16) "analysis of foot"
}
]
Here's what I was thinking that doesn't seem to work:
function suppress_name($name){
global $string;
return ($name == $string) ? '' : $string;
}
function overall() {
//$result = database call to get objects
foreach ($result as $item) {
$string = $item->lastName;
$rows = array('Name' => suppress_name($item->lastName), 'project' => $item->projectName);
}
}
Researching I see several references to array_unique() which I use for a flattened array, but I can't see that it would help me here. OK, I thought I could make a function, like the above, to handle duplicates and use the $global but think I'm not grasping how to use globals in this instance. I'm happy to be pointed to a better way, or better search terms. Does this make sense?
Here is a possible approach to your solution, where we store the last names in a one dimensional array then check against it through each iteration of the array. If the lastName is in the array then set the value to ''.
Note the use of the reference (&).
<?php
$arrays = array(
array('lastName' => 'w', 'projectName' => 'Bone density scanner analysis'),
array('lastName' => 'w', 'projectName' => 'analysis of foot')
);
$last_names = array();
foreach($arrays as &$array){
if( in_array($array['lastName'],$last_names) ){
$array['lastName'] = '';
}else{
$last_names[] = $array['lastName'];
}
}
echo '<pre>',print_r($arrays),'</pre>';
It would be easier to work with nested arrays
array [
0 => {
["lastName"]=> string(1) "w"
["projects"]=> array [
0 => {
["projectName"] => string(29) "Bone density scanner analysis"
}
1 => {
["projectName"]=> string(16) "analysis of foot"
}
1 => {
["lastName"] => string(1) "x"
["projects"] => array [
0 => {
["projectName"] => string(16) "analysis of head"
} ]
}
]

PHP how to echo array values which have no name attached to them

How can I put each value into a variable?
I tried using foreach but I am not sure what to put in the ??? area
I tried also using echo $results[14], but I received an undefined error.
foreach($results['ups'] as $result) {
echo $result['???']. '<br>';
}
output:
array(1) {
["ups"]=> array(4) {
[14]=> string(5) "62.89"
["01"]=> string(5) "30.47"
["02"]=> string(5) "20.76"
[11]=> string(5) "20.96"
}
}
Array
(
[ups] => Array
(
[14] => 62.89
[01] => 30.47
[02] => 20.76
[11] => 20.96
)
)
You put nothing in the []:
foreach($results['ups'] as $result) {
echo $result + '<br>';
}
should do it.
array_keys() should return all defined keys, so try eg.
$keys = array_keys($results['ups']);
echo $results['ups'][$keys[0]];
echo $results['ups'][$keys[1]];
to access the first and second element.
simply use
echo $results['ups']['14'];
if you don't know the index that you want to access or maintaining key index is not relevant.
sort $results['ups'];
echo $results['ups'][0];

How to randomize an array of objects in PHP?

I have this example of an array of objects and I need to randomize it each time I do a foreach loop.
Looks like shuffle works only on arrays.
One thing is that I cant convert this into an array, because then it will become a STD object which I can't use, because of the way my mapper works.
array(48) {
[0] => object(Friends_Model_Friends)#142 (4) {
["_id":protected] => NULL
["_tal":protected] => object(stdClass)#194 (3) {
["thumb"] => object(stdClass)#196 (6) {
["id"] => string(8) "10884697"
["type"] => string(1) "2"
["gallery"] => string(1) "1"
}
}
["_friend":protected] => string(7) "3492149"
["_dependent_table":protected] => NULL
}
[1] => object(Friends_Model_Friends)#195 (4) {
["_id":protected] => NULL
["_tal":protected] => object(stdClass)#143 (3) {
["thumb"] => object(stdClass)#202 (6) {
["id"] => string(8) "11160632"
["type"] => string(1) "2"
["gallery"] => string(1) "1"
}
}
["_friend":protected] => string(7) "3301541"
["_dependent_table":protected] => NULL
}
....
Any ideas on shuffling this?
edit: Zend_Debug::dump(shuffle($object)); returns bool(true)
<?php
$my_array;
echo '<pre>'; print_r($my_array); echo '</pre>';
shuffle ($my_array);
echo '<pre>'; print_r($my_array); echo '</pre>';
?>
Try this code
But the objects are in an array, not another object so you can use shuffle...
Shuffle always returns a boolean:
bool shuffle ( array &$array )
So you can't return it like
return shuffle( $myAwesomeArray );
This is what I just did and I wondered why it didn't give anything back, as you're probably expecting your shuffled array back.
You just have to call it like this
shuffle( $myAwesomeArray );
return $myAwesomeArray;
And all should work just fine.

PHP radom output from key value array

How can I get the follow thing done.
The follow array I have:
array(2) { [0] => array(3) {
["id"] => string(1) "5"
["avatar"] => string(15) "4e0d886ee9ed3_n"
["username"] => string(5) "testuser1"}
[1] => array(3) {
["id"] => string(1) "1"
["avatar"] => string(15) "4e25bc58b6789_w"
["username"] => string(6) "testuser2"
}
}
I want to create a array with just one user in it, but it has to be random. It can be like
user with id=5, id=1 or a hole other user (when there are more users).
Did you try, something like:
$rand = array_rand($your_array);
http://fr2.php.net/manual/en/function.array-rand.php
Try using array_rand().
$randomKey = array_rand($yourArray);
$randomUserId = $yourArray[$randomKey]['id'];
Simple.
$rand_user = array_rand($your_array);
PHP Manual: array_rand

PHP Unable to echo ID field from MySQL database

I'm trying to print an ID from MySQL, the field loads into an array and is visible via print_r but I can't echo it or transfer it to another variable ... what am I missing?
if ( $_POST['section'] == "freelance" ) {
$field_name = "promoter";
} else {
$field_name = "connector";
}
echo $row[$field_name.'_login_ID']
As requested the results of var_dump($row)
array(13) {
["connector_login_id"] => string(2) "14"
["connector_type"] => string(10) "non-profit"
["unique_code"] => string(9) "test-t001"
["update_code"] => string(1) "N"
["md5ID"] => string(0) ""
["username"] => string(6) "bugger"
["connectorEmail"] => string(17) "gzigner#gmail.com"
["password"] => string(32) "098f6bcd4621d373cade4e832627b4f6"
["connectorPass"] => string(4) "test"
["active"] => string(1) "Y"
["modified"] => string(19) "2009-08-21 15:37:22"
["lastlogin"] => string(19) "0000-00-00 00:00:00"
["md5email" ]=> string(32) "051cba58da33fac6b2d18af5182079f4"
}
$row[$field_name.'_login_ID'] <-- "ID"
array(13) {
["connector_login_id"] <-- "id"
Seems like a simple typo to me.
Alternatively, are you sure $field_name gets set to 'connector', since 'promoter_login_id' doesn't exist in this array.
This is purely speculation without your code, but it's probable that the field you are trying to echo contains a hyphen, e.g. "mytable-id", considering that it does indeed show when you use print_r() to print out the entire array. If this is the case you would need to use {'mytable-id'} to get/echo it's value:
echo($dataArray->MyTable->{'mytable-id'});
*Edit: I don't know if your code is copy and pasted, but the value you are trying to print is:
echo $row[$field_name.'_login_ID'];
instead of:
echo $row[$field_name.'_login_id'];
PHP is case-sensitive. You could also try this:
$field_name = $field_name.'_login_id';
echo $row[$field_name];
or
$field_name = $field_name.'_login_id';
echo $row['$field_name'];

Categories