creating key=>value pairs with foreach loops - php

here's my issue:
I have a program in the command line that has access to tens of thousands of users. The idea is that you want to be able to get all the information about a user by simply inputting their username. So, because I want to work in php, I've done the following
$user_info = array();
exec('uwdir -v userid=nvidovic', $user_info);
To give you an oversimplified version of what a var_dump on $user_info would look like, it would be something like this:
array(2){
[0] => "first: N"
[1] => "last: Vidovic"
}
I'd like to be able to do this $user[first] => N
This is what I've come up with (not for the real data from command line):
$full_name = array("first: N", "last: Vidovic");
var_dump($full_name);
foreach ($full_name as $part_name) {
$exploded = explode(":", $part_name);
$make_array = array($exploded[0] => $exploded[1]);
echo $make_array["first"];
}
Clearly, this doesn't work. But my question is why? Does anyone know how I can do what I explained above?
I'm really, really, really...really stuck
THANKS to anyone in advance!!
EDIT:
Great answers, thank you. One last thing though, I keep getting the error messages Notice: Undefined offset: 1 and Notice: Undefined offset: 0 for the code below:
$user_info = array();
exec('uwdir -v userid=nvidovic', $user_info);
foreach ($user_info as $info) {
$exploded_info = explode(":", $info);
$info_array[$exploded_info[0]] = $exploded_info[1];
}
echo $info_array["displayName"];
Anyone know why this is happening? I thought the explode function would break up the single string into an array of two strings, right?

Instead of
$make_array = array($exploded[0] => $exploded[1]);
try
$make_array[$exploded[0]] = $exploded[1];
Make sure you put $make_array = array(); before this line, just to make sure it's an empty array.

$full_name = array("first: N", "last: Vidovic");
//var_dump($full_name);
foreach ($full_name as $part_name) {
$exploded = explode(":", $part_name);
$make_array[$exploded[0]] = $exploded[1];
// echo $make_array["first"];
}
print_r($make_array);
http://codepad.org/JvcPdBeq

Because the line
$make_array = array($exploded[0] => $exploded[1]);
overwrites the contents of the whole array. So on the last step you will have only one element there.

Related

Array key with the dash php 5

In my code in php 5 I need to access array key which have a dash in its name(case-ins). Is there any way to do that?
My code looks like this:
$count = 0;
foreach($par as $key){
foreach($key as $case-ins)
$count = $count+1;
....
}
Basically I need to get array size. I know I can probably use the count function, but right now the biggest problem I am dealing with is the dash. I have found on the internet something like ${case-ins}. but it didn't work. I can't change name of array key because it is actually argument from command line which I got using getopt.
Could you please help me with this? Or is there any other way around to count how many times was same argument used?
Thank you for all the answers :)
$par = array(
array(
'0'=> 'dark-blue',
'1'=> 'yellow',
'2'=> 'high-color'
),
);
$count = 0;
foreach ($par as $key ) {
foreach ($key as ${'case-ins'} ) {
if (preg_match('#-#', ${'case-ins'} )==true) {
$count = $count+1;
}
}
}
echo $count; // count is 2 ..
More info: in some strict PHP systems you better use #(.+)?-(.+)?# instead of #-#
and instead of ${'case-ins'} you may use normal variables like $case_ins, not dash in PHP.

update element in php foreach

I know this should be very simple, but boy I'm making a mess of it... would be great if someone could point me in the right direction.
I've got an array which looks like this:
print_r($request_attributes['length']);
Array
(
[0] => 28.00000
[1] => 18.00000
)
and am trying to modify like so:
if(is_array($request_attributes['length'])) {
$request_attributes['length'] = $request_attributes['length'][0];
print($request_attributes['length']);
$request_attributes['length'] = $request_attributes['length'][1];
print($request_attributes['length']);
}
which gives the correct output in the first update, but the second item outputs an '8'. I've tried the above in both a for and foreach which results in similar output for both this and the other two arrays ( width(8) and height(0) - they should result in 18.00000 and 13.00000 respectively ). So I guess I really have two questions:
1. How do I update this(these) element(s)?
2. Where are the funny outputs actually coming from?
If anyone can help, I'd really appreciated it.
Just have a look at this. Your problem is, that you override you variable and in the second step $request_attributes['length'] is a string. Just define another var for your values.
$request_attributes['length'] = [
28.000,
18.000
];
$attributes = array();
if (is_array($request_attributes['length'])) {
foreach ($request_attributes['length'] as $value) {
$attributes[] = $value;
}
}
As you see $attributes will contain all values of your $request_attributes['length'] array and will not be overwritten.
Define araay as below
$val=array([0]=>"18.000",[1]=>13.000)
then use
if(is_array($request_attributes['length'])) {
$request_attributes['length'] = $val;
print_r($request_attributes['length']);
$request_attributes['length'] = $val;
print_r($request_attributes['length']);
}
Previously your array doesnt have any name.
Your print will only return Just array not the values
use
print_r($request_attributes['length']) ;
instead

foreach () Error

I'm getting the following warning when running this script:
Warning: Invalid argument supplied for foreach()
This is the script:
$values = array();
foreach ($_POST['rights'] as $right_id)
{
$values[] = '(' . $id . ', ' . $right_id . ')';
}
$_POST['rights']/$id are integers. In this case it was $_POST['rights'] = 1,2,3,4,5; $id = 2.
The strange part is that on a different page with the same kind of input it gives no errors.
The question: What is wrong with it?
check $_POST['rights']
var_dump($_POST['rights']);
I think $_POST['rights'] is not an array.
foreach must take an array, you're passing it an integer. You can't iterate over an integer.
A wise move might be to check whatever you're about to iterate over is indeed an array:
if(is_array($_POST['rights'])){
foreach($_POST['rights'] as $value){
//Whatever you want to do with each $value
}
}
else {
//Let the user know it's hit the fan…
throw new Exception('Help, I\'m not an array :(')
}
PHP docs for arrays: http://php.net/manual/en/language.types.array.php
PHP docs for foreach: http://php.net/manual/en/control-structures.foreach.php
As per your statement $_POST['rights'] is not an array.
It is probably a simple string having 1,2,3,4
You need to convert it into an array with explode function.
e.g
$_POST['rights'] = explode(",", $_POST['rights']);
Then your for loop will work.
The passed array $_POST['rights'] probably is empty.
EDIT:
Like Mark Baker said an empty array is fine. You should go with the other answers.

Accessing an array in an object

If i knew the correct terms to search these would be easy to google this but im not sure on the terminology.
I have an API that returns a big object. There is one particular one i access via:
$bug->fields->customfield_10205[0]->name;
//result is johndoe#gmail.com
There is numerous values and i can access them by changing it from 0 to 1 and so on
But i want to loop through the array (maybe thats not the correct term) and get all the emails in there and add it to a string like this:
implode(',', $array);
//This is private code so not worried too much about escaping
Would have thought i just do something like:
echo implode(',', $bug->fields->customfield_10205->name);
Also tried
echo implode(',', $bug->fields->customfield_10205);
And
echo implode(',', $bug->fields->customfield_10205[]->name);
The output im looking for is:
'johndoe#gmail.com,marydoe#gmail.com,patdoe#gmail.com'
Where am i going wrong and i apologize in advance for the silly question, this is probably so newbie
You need an iteration, such as
# an array to store all the name attribute
$names = array();
foreach ($bug->fields->customfield_10205 as $idx=>$obj)
{
$names[] = $obj->name;
}
# then format it to whatever format your like
$str_names = implode(',', $names);
PS: You should look for attribute email instead of name, however, I just follow your code
use this code ,and loop through the array.
$arr = array();
for($i = 0; $i < count($bug->fields->customfield_10205); $i++)
{
$arr[] = $bug->fields->customfield_10205[$i]->name;
}
$arr = implode(','$arr);
This is not possible in PHP without using an additional loop and a temporary list:
$names = array();
foreach($bug->fields->customfield_10205 as $v)
{
$names[] = $v->name;
}
implode(',', $names);
You can use array_map function like this
function map($item)
{
return $item->fields->customfield_10205[0]->name;
}
implode(',', array_map("map", $bugs)); // the $bugs is the original array

PHP arrays. inserting "$key" => "$value" pair into array with array_push();

Why won't this work?
$slidetotal=1;
$slideids = array();
while ($rowcs = mysql_fetch_array($orig_slides_result)) {
$key = $slidetotal;
array_push($slideids[$key], $rowcs['id']);
$slidetotal++;
}
I get this error:
[phpBB Debug] PHP Notice: in file ///*.php on line 161: array_push() [function.array-push]: First argument should be an array
Although someone has commented you can do this on this page:
http://php.net/manual/en/function.array-push.php , (find: "to insert a "$key" => "$value" pair into an array")
What is the next best way to insert a list of single values into a php array? By the way, I really can't believe it's hard to find something on this with google.com. Seriously?
That PHP.net comment is incorrect. That is pushing $rowcs['id'] onto the array $slideids[$key], not the array $slideids.
You should be doing the following, in place of your array_push() call:
$slideids[$key] = $rowcs['id'];
Why don't you do;
$slidetotal=1;
$slideids = array();
while ($rowcs = mysql_fetch_array($orig_slides_result)) {
$slideids[$slidetotal] = $rowcs['id'];
$slidetotal++;
}
Also you can do like below if you don't need the key to start from 1;
$slideids = array();
while ($rowcs = mysql_fetch_array($orig_slides_result)) {
$slideids[] = $rowcs['id'];
}
ummm hard-searching will work for google I think :)
anyway, error tells you everything you need to know. that means first argument of array_push is not an array, you give a single value (string) to array_push ($slideids[$key]).
Also why do you need to use array_push in php? I'd rather use
$slideids[] = $rowcs['id'];
and what you're trying to do is:
$slideids[$key] = $rowcs['id'];
i guess...

Categories