Put simply, I need to take the first column of an array and turn that into a named array, multiple times over within a single 2d array.
$arr[0][0] = "Name" $arr[1][0] = "Version" ...etc, allowing me to then access them as: $arr["Name"][1] = "Bob" $arr["Version"][1] = "1.00"
How do you assign variable names to an index? If that makes sense. I don't know the proper terms for this kind of thing... Or at least not how to use them.
Anyway, the actual array looks like this:
Name,Version,Compact,OpenGFx
Element1,1.0,0,0,1
Element2,1.23,0,0,1
ElementN,1.0,0,0,1
I started writing identifiers to do the same thing ($name=0, $version=1, etc.) but there are 165 columns ! So automation would be much easier, and I am interested in learning new things as always!
If I understand it right, you don't want to be writing out all of the headings right? Maybe you could do something similar to this code:
I've just assumed the format of the input array, you might need to change it around a bit:
$input = array(
array('name', 'version', 'compact'), // and so on
array('element1', 1.0, 0),
array('element2', 1.3, 1) // and so on
);
$headings = array_shift($input);
$output = array();
foreach ($input as $row) {
$newrow = array();
foreach ($headings as $index => $name) {
$newrow[$name] = $row[$index];
}
$output[] = $newrow;
}
var_dump($output);
$array = array();
// add your values to the last index
$array['Name'][] = 'Counter Strike';
$array['Version'][] = '1.6';
$array['Name'][] = 'Bob';
$array['Version'][] = '1.0';
// display results
echo $array['Name'][0]; // Counter Strike
echo $array['Version'][0]; // 1.6
echo $array['Name'][1]; // Bob
echo $array['Version'][1]; // 1.0
// sexier way
$element1 = array('Name' => 'Counter Strike', 'Version' => '1.6');
$element2 = array('Name' => 'Bob', 'Version' => '1.0');
// add the element
$array[] = $element1;
$array[] = $element2;
// or
array_push($array, $element1);
array_push($array, $element2);
// display with a loop
foreach ($array as $element) {
echo $element['Name'];
echo $element['Version'];
}
// or
echo $array[0]['Name']; // Counter Strike
echo $array[1]['Name']; // Bob
ok what you do is:
$arr = array();
$arr['NAME'] = array();
$arr['VERSION'] = array(); //and so on
//to add to the array:
$arr['NAME'][] = 'john';
//or
$arr['NAME'][0] = 'john';
//etc etc
And then to print all the Names (for example) you can do:
foreach($arr['NAME'] as $name){
echo $name.'<br/>';
}
I think you want to do your array like this:
$arr[] = array("name" => "nameValue"
, "version" => 1
, "compact" => 0 ) //...etc
then you can access it like this:
$currentName = $arr[0]['name'];
$currentVersion = $arr[0]['version'] //...etc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.