I've been trying to figure out how to separate these items.. I'm getting a full array like this:
array = ('name' => 'test', 'last name' => 'test' , 'name' => 'test1');
But i need it this way: (Example not well typed)
0[('name' => 'a name', 'lastname' => 'a last name')], 1[('name' => 'a name', 'last name' => 'a last name')]
I only need to find one string and the last name behind that string. I can't transform the array because it's from a real big XML file.
thanks for your help guys.
I've found a real easy solution. Stupid of me!
$array = array($items['name'] => $items['last_name']);
Related
How Can I Create a main array that includes multiple child array And be in the form of Jason and I want to add the child Array to main array in the Loop
MainArray=[
array1=[{fname:asdada,lastname:sdsadasda}];
array2=[{fname:asdada,lastname:sdsadasda}];
array3=[{fname:asdada,lastname:sdsadasda}];
];
echo MainArray[1]->fname;
Please see the following pseudo code below:
pseudo code
You should really look into a basic php tutorial.
This is how you do it.
$mainArray = [
'array1' => ['fname' => 'asdada', 'lastname' => 'sdsadasda'],
'array2' => ['fname' => 'asdada', 'lastname' => 'sdsadasda'],
'array3' => ['fname' => 'asdada', 'lastname' => 'sdsadasda']
];
echo $mainArray['array1']['fname'];
Or use the long notation if you have an older version of php or want backwards compatibility.
$mainArray = array(
'array1' => array('fname' => 'foo', 'lastname' => 'bar'),
'array2' => array('fname' => 'lorem', 'lastname' => 'ipsum'),
'array3' => array('fname' => 'test', 'lastname' => 'example')
);
echo $mainArray['array1']['fname'];
Explanation:
The php variable sigil is $. This means that in order to access a variable or assign something to a variable, you use $mainArray. See more on variables in the documentation.
The php array can be used in two different notations. Either array(...) or, from php 5.4 upwards, [...]. Other than the opening and closing parts, they are identical. You don't use : or = to assign individual values inside an array declaration. For this you use the => operator. Each element in an array is separated by a comma (,).
E.g.
$mainArray = array(
'A' => 1,
'B' => 2
];
Arrays in Php can be either associative or numerical. What you probably want is that your outer array is numerical, meaning you can access it using $mainArray[1], and your inner array is associative. For numerical arrays, you don't specify a key yourself, so there is no need for the =>.
$mainArray = array(
array(),
array(),
array()
);
And with associative sub arrays this becomes:
$mainArray = array(
array('firstname' => 'foo', 'lastname' => 'bar'),
array('firstname' => 'test', 'lastname' => 'example'),
array('firstname' => 'lorem', 'lastname' => 'ipsum')
);
In order to access the firstname key of the first child array in this multilevel array structure, you do:
$mainArray[0]['firstname']
E.g. (if you want to echo it to the standard output)
echo $mainArray[0]['firstname'];
Please note that numerical arrays in php start counting on 0, as in most other programming languages. And please note that the key in the associative array is a string, and as such must be surrounded with either ' or ".
I can recommend you search for a php beginner's tutorial and try to write and execute the examples yourself, to get a better grasp of php. If you need somewhere to run your php examples, I can recommend you try an online php environment such as PHPFiddle.
Update on adding values:
You can add more key=>value pairs to an associative array or add more values to a numerical array afterwards in much the same way as you would access or assign to it.
First, let's add a value to a numerical array. You do this by adding [] to the end of your variable when assigning. This means that what you assign will be added as a new numerical value to the end of your array.
$numericalArray = array(
7,
8,
6,
12,
'B'
);
$numericalArray[] = 'C';
// Results in the array: array(7, 8, 6, 12, 'B', 'C')
And in order to add a new key => value pair to an associative array, you just add it using the new key, e.g.
$assoc = array(
'firstname' => 'Testy',
'lastname' => 'McTestface'
);
$assoc['middlename'] => 'Tester';
So to add a new fname-lastname pair to the mainArray, you would do:
$mainArray = array(
array('fname' => 'foo', 'lastname' => 'bar'),
array('fname' => 'test', 'lastname' => 'example'),
array('fname' => 'lorem', 'lastname' => 'ipsum')
);
$mainArray[] = array('fname' => 'new name', 'lastname' => 'new last name');
If you want to do this in a loop, you will use the for, foreach, while or do while structures.
E.g.
$mainArray = array(
array('fname' => 'foo', 'lastname' => 'bar'),
array('fname' => 'test', 'lastname' => 'example'),
array('fname' => 'lorem', 'lastname' => 'ipsum')
);
for ($i = 0; $i < 3; ++$i) {
$mainArray[] = array('fname' => 'new name ' . $i, 'lastname' => 'new last name ' . $i);
}
echo json_encode($mainArray, JSON_PRETTY_PRINT|JSON_UNESPACED_UNICODE|JSON_UNESCAPED_SLASHES), PHP_EOL;
// [
// {'fname': 'foo', 'lastname': 'bar'},
// {'fname': 'test', 'lastname': 'example'},
// {'fname': 'lorem', 'lastname': 'ipsum'},
// {'fname': 'new name 0', 'lastname': 'new last name 0'},
// {'fname': 'new name 1', 'lastname': 'new last name 1'},
// {'fname': 'new name 2', 'lastname': 'new last name 2'},
// ]
<?
$categoriesID = array("popular","old");
$product => array (
Product 1
'categoryID' => $categoriesID[1],
'Name' => 'Product One',
Product 2
'categoryID' => $categoriesID[2],
'Name' => 'Product Two',
Product 3
'categoryID' => $categoriesID[2],
'Name' => 'Product Two',
Product 4
'categoryID' => $categoriesID[2],
'Name' => 'Product Two',
);
How can I loop through this to reflect that product 1 belongs to category 1, product 2 belongs to category 2, product 3 belongs to category 2 and so on?
I tried the following but no luck..
foreach($product as $key => $pro){
var_dump($categoriesID[$key]);
}
I would really appreciated any suggestions or how what i'm doing wrong.The goal is to insert the relationship into a database table where in order to insert a product a category_id is required.
Your arrays are not written correctly. You got a multi dimensional array here (arrays inside of an array). Read this to understand how they are written and how you can work with them: http://php.net/manual/en/language.types.array.php
If your categories are numeric you should also consider to use numeric values: 1 instead of '1' inside of the $categoriesID array or depending on the database auto casting capability you will get issues inserting strings as decimals.
Here is your given code modified as working example. Ive changed the var_dump output for better readability of the result.
Ive also changed the array indexes you have used since arrays start at 0. If you need the numbers still to start at 1 you could add some nonsense value at the beginning of the array or subtract 1 when accessing the array. Keep in mind that this is an quick & dirty solution to the given problem.
Nevertheless as Patrick Q said you should consider some introduction to PHP.
<?php
$categoriesID = array('1','2');
$product = array (
array(
'categoryID' => $categoriesID[0],
'Name' => 'Product One',
),
array(
'categoryID' => $categoriesID[1],
'Name' => 'Product Two',
),
array(
'categoryID' => $categoriesID[1],
'Name' => 'Product Two',
),
array(
'categoryID' => $categoriesID[1],
'Name' => 'Product Two',
)
);
foreach($product as $key => $value){
echo var_export($value, true) . '<br>';
}
You could further edit Mariusz's answer to do something like this:
foreach($product as $item){
echo $item['Name'].' - '.$item['categoryID'].'<br>';
}
This would give you easy access to both product name and category ID.
I have a list of codes that need to replace values in an array. This process should leave the other elements in the array unchanged. For example, I have an array that looks like this:
$data=array(
'container_label_1' => '1 gallon',
'container_num_1' => '1',
'container_label_2' => '5 gallon',
'container_num_2' => '1',
'container_label_3' => '2',
'container_num_3' => '5 gallon' );
And I have a second array of variable length that looks like this
$modifier=array(
'1 gallon'=>'1 gallon code',
'5 gallon'=>'5 gallon code',
'10 gallon'=>'10 gallon code'
in the format of:
label value to be replaced=>code
(In actual use the code values I'm using here would be something else that didn't include the container size.)
I want the array to look like this when it's done:
$data=array(
'container_label_1' => '1 gallon code',
'container_num_1' => '1',
'container_label_2' => '5 gallon code',
'container_num_2' => '1',
'container_label_3' => '2',
'container_num_3' => '5 gallon code');
It should only modify container labels (container_label_1, container_label_2,container_label_3, etc). The items in the $modifier array will not necessarily be in the $data array as shown in the example.
It seems like there should be a fairly simple way to accomplish this, but I'm just not thinking of it. I've tried looking for similar cases on here and in the php.net documentation and I was thinking about using array_map, but I just can't seem to wrap my head around how this would work with my situation. I'm looking for something that's more efficient than checking every array item for each item in the modifier array as these arrays are much larger than the example.
I saw something that looked promising here:
http://www.php.net/manual/en/function.array-replace.php
steelpandrummer's post seems to do something close to what I want, but it compares keys and I need to compare values, not keys. I can't do an array flip because my values are not often going to be unique. And array flip would thus lose data.
Any help would be appreciated.
Actually, array_map works ok :
$data = array(
'container_label_1' => '1 gallon',
'container_num_1' => '1',
'container_label_2' => '5 gallon',
'container_num_2' => '1',
'container_label_3' => '2',
'container_num_3' => '5 gallon'
);
function replaceValues($val) {
$modifier = array(
'1 gallon' => '1 gallon code',
'5 gallon' => '5 gallon code',
'10 gallon' => '10 gallon code'
);
return isset($modifier[$val]) ? $modifier[$val] : $val;
}
print_r(array_map('replaceValues', $data));
Result is
Array
(
[container_label_1] => 1 gallon code
[container_num_1] => 1
[container_label_2] => 5 gallon code
[container_num_2] => 1
[container_label_3] => 2
[container_num_3] => 5 gallon code
)
Clean version with lambda function:
array_walk($data, function(&$v, $k) {
global $modifier;
$v = array_key_exists($v, $modifier) ? $modifier[$v] : $v;
});
I currently have an array set up like this:
$u_id= array(
array(
NUM=>'2770', DESC=>'description one'
),
array(
NUM=>'33356', DESC=>'description two'
),
array(
NUM=>'13576', DESC=>'description three'
),
array(
NUM=>'14141', DESC=>'description four'
)
);
I need to be able to pass a number through this array as $num (corresponding to a NUM=>'' in the array), and store the corresponding DESC=>'' as a string. For example, searching for "2770" would return "description one".
What would be the best way to go about doing this?
Are you constrained to this array structure? Because a more efficient structure would be to just do
$u_id= array(
'2770' => 'description one',
'33356' => 'description two',
'13576' => 'description three',
'14141' => 'description four'
);
That is to say, you just assume that the key is the number and the value is the description, rather than naming them explicitly. Then the code to find the correct description is just $u_id[2770] (or whichever).
If that's not acceptable, you could also do
$u_id= array(
'2770' => array(
NUM=>'2770', DESC=>'description one'
),
'33356' => array(
NUM=>'33356', DESC=>'description two'
),
'13576' => array(
NUM=>'13576', DESC=>'description three'
),
'14141' => array(
NUM=>'14141', DESC=>'description four'
)
);
That is, the number is also used as the key to find the correct pair. The code to find the correct description becomes $u_id[2770]["NUM"].
In either of these scenarios, finding a given description from the number is a single step. If you can't change the array structure, though, then you'd have to loop through the array to check (which could take as many steps as there are items in the array).
foreach($arrays as $arr){
if($arr['NUM']==$num){
return $arr['DESC'];
}
}
I have data from a form submission stored in a variable called $post_data. When I do print_r($post_data); I get the following array:
Array
(
[element_3] => John Doe
[element_2] => john#example.com
[element_14] => City
[element_15] => Country
[form_id] => 1
[submit] => Submit
);
I want to store some of the fields in another array to pass to another script. Will my code below work? If not, how do I fix it?
$submitted_data = array(
'Fields' => array(
array(
'Key' => 'Name',
'Value' => $post_data['element_3']
)
array(
'Key' => 'Email',
'Value' => $post_data['element_2']
)
)
)
Also, a PHP noob question, do I need another comma (,) in between the Name and Email array?
Thanks!
I'm not exactly sure why you would want to do this, but depending on the field name you can consider using loops to help automate the entire process.
$field_map = array(
'element_3' => 'Name',
'element_2' => 'E-mail',
'element_14' => 'City',
'element_15' => 'Country'
);
$submitted_data = array('fields' => array());
foreach ( $field_map as $key => $label)
{
$submitted_data['fields'][] = array(
'key' => $key, // e.g. element_2
'label' => $label, // e.g. E-mail
'value' => $post_data[$key] // e.g. john#example.com
);
}
This separates the storage/mapping of key/label pairs from the part which processes it, making it easier to maintain and modify in the future.
Another way might be (depending on how "fixed" the second script is, if you can alter it).
$submitted_data['Name']=$post_data['element_3'];
$submitted_data['Email']=$post_data['element_2'];
To get a result more like the one in your question:
$submitted_data['Fields']['0']['Key']='Name';
$submitted_data['Fields']['0']['Value']=$post_data['element_3'];
$submitted_data['Fields']['1']['Key']='Email';
$submitted_data['Fields']['1']['Value']=$post_data['element_2'];