I have an array which contains information on posts I have made.
$DexArray = array(
array(
'url' => "http://i.imgur.com/ObXLdd6C.jpg",
'headline' => "Dronningens Nytårstale",
'subline' => "Tallene bag talen og årets spilforslag",
'href' => "nytaarstale.php",
'postedby' => "kris",
'postedurl' => "https://www.facebook.com/dataanalyticsdk",
'dato' => "21. december, 2014"
),
array(
'url' => "http://i.imgur.com/sxddhOe.jpg",
'headline' => "Endless Jewelry",
'subline' => "Are there really endless possibilities?",
'href' => "endless.php",
'postedby' => "Nikolaj Thulstrup",
'postedurl' => "kris",
'dato' => "10. december, 2014"
),
It is stored in a multidimensional associate array. I am trying to retrieve a random 'href' value in the array and store it as a variable.
I have tried using the array_rand function but it doesn't seem to work.
$k = array_rand($DexArray);
$v = $array[$k]['href'];
I get an error message saying: undefined variable: array in this line "$v = $array[$k]['href'];"
Do you have a solution for this?
It should be
$k = array_rand($DexArray);
$v = $DexArray[$k]['href'];
Here's a working debug :) link
There was a lingering , in your thingy. And $array was never defined in the first place, so that's what the error was telling you about.
Execute the code it will return the random value from the multidimensional php array.
<?php
$filter_field = array();
$original_items = array(
array(1, 'stuff1', 'info1', 'response1', 'info1', 'response1'), array(2, 'stuff2', 'info2', 'response2', 'info2', 'response2'), array(3, 'stuff3', 'info3', 'response3', 'info3', 'response3'), array(4, 'stuff4', 'info4', 'response4', 'info4', 'response4'));
for ($x = 0; $x < sizeof($original_items); $x++) {
array_push($filter_field, $original_items[$x][0]);
}
shuffle($filter_field);
echo "<br/><br/><br/>";
for ($x = 0; $x < sizeof($original_items); $x++) {
$k = $filter_field[$x];
for ($y = 0; $y < 5; $y++) {
echo $original_items[$k-1][$y];
}
echo "<br/><br/>";
}
?>
Here is another solution that will return the index of the random array.
$var = array(
array("a", "one"),
array("b", "two"),
array("c", "three"),
array("d", "four"),
array("e", "five"),
array("f", "six"),
array("g", "seven")
);
// array_rand returns the INDEX to the randomly
// chosen value, use that to access the array.
$finalVar = $var[array_rand($var)];
print_r($finalVar);
Related
I have a already defined array, containing values just like the one below:
$arr = ['a','b','c'];
How could one add the following using PHP?
$arr = [
'a' => 10,
'b' => 5,
'c' => 21
]
I have tried:
$arr['a'] = 10 but it throws the error: Undefined index: a
I am surely that I do a stupid mistake.. could someone open my eyes?
Full code below:
$finishes = []; //define array to hold finish types
foreach ($projectstages as $stage) {
if ($stage->finish_type) {
if(!in_array($stage->finish_type, $finishes)){
array_push($finishes, $stage->finish_type);
}
}
}
foreach ($projectunits as $unit) {
$data[$i] = [
'id' => $unit->id,
'project_name' => $unit->project_name,
'block_title' => $unit->block_title,
'unit' => $unit->unit,
'core' => $unit->core,
'floor' => $unit->floor,
'unit_type' => $unit->unit_type,
'tenure_type' => $unit->tenure_type,
'floors' => $unit->unit_floors,
'weelchair' => $unit->weelchair,
'dual_aspect' => $unit->dual_aspect
];
$st = array();
$bs = '';
foreach ($projectstages as $stage) {
$projectmeasure = ProjectMeasure::select('measure')
->where('project_id',$this->projectId)
->where('build_stage_id', $stage->id)
->where('unit_id', $unit->id)
->where('block_id', $unit->block_id)
->where('build_stage_type_id', $stage->build_stage_type_id)
->first();
$st += [
'BST-'.$stage->build_stage_type_id => ($projectmeasure ? $projectmeasure->measure : '0')
];
if (($stage->is_square_meter == 0) && ($stage->is_draft == 0)) {
$height = ($stage->height_override == 0 ? $unit->gross_floor_height : $stage->height_override); //08.14.20: override default height if build stage type has it's own custom height
$st += [
'BST-sqm-'.$stage->build_stage_type_id => ($projectmeasure ? $projectmeasure->measure * $height: '0')
];
if ($stage->finish_type) {
$finishes[$stage->finish_type] += ($projectmeasure ? $projectmeasure->measure * $height: '0') * ($stage->both_side ? 2 : 1); //error is thrown at this line
}
} else {
if ($stage->finish_type) {
$finishes[$stage->finish_type] += ($projectmeasure ? $projectmeasure->measure : '0');
}
}
}
$data[$i] = array_merge($data[$i], $st);
$data[$i] = array_merge($data[$i], $finishes[$stage->finish_type]);
$i++;
}
The above code is used as is and the array $finishes is the one from the first example, called $arr
You're using += in your real code instead of =. That tries to do maths to add to an existing value, whereas = can just assign a new index with that value if it doesn't exist.
+= can't do maths to add a number to nothing. You need to check first if the index exists yet. If it doesn't exist, then assign it with an initial value. If it already exists with a value, then you can add the new value to the existing value.
If you want to convert the array of strings to a collection of keys (elements) and values (integers), you can try the following:
$arr = ['a','b','c'];
$newVals = [10, 5, 21];
function convertArr($arr, $newVals){
if(count($arr) == count($newVals)){
$len = count($arr);
for($i = 0; $i < $len; $i++){
$temp = $arr[$i];
$arr[$temp] = $newVals[$i];
unset($arr[$i]);
}
}
return $arr;
}
print_r(convertArr($arr, $newVals));
Output:
Array ( [a] => 10 [b] => 5 [c] => 21 )
This is quite basic, but I am missing a puzzle piece.
I have a multidimensional PHP array that - among other things - contains some strings. I would like to translate special strings in this array based on a translation table or array in PHP.
$r = array(
0 => 'something',
1 => array(
'othertext' => '1000 {{animals}} and {{cars}}',
'anytext' => '400 {{cars}}',
)
);
In $r, now I would like to replace {{animals}} with another string that is stored in a separate array.
Here it is:
$translations = array(
'animals' => array('Tiere','animaux','bestie'),
'cars' => array('Autos','voitures','macchine'),
);
Now let's set the language / column we want to look up
$langId = 0;
And now, take $r, look for all key that are wrapped in {{}}, look them up in $translations and replace them with key[$langId], so in return we get:
$r = array(
0 => 'something',
1 => array(
'othertext' => '1000 Tiere',
'anytext' => '400 Autos',
)
);
ehm... how's that done?
PS: the marker {{}} is random, could be anything robust
I was able to get the output you expected using the following code. Try it and tell me if it worked for you or not:
<?php
$r = array(
0 => 'something',
1 => array(
'othertext' => '1000 {{animals}} and {{cars}}',
'anytext' => '400 {{cars}}',
)
);
$translations = array(
'animals' => array('Tiere','animaux','bestie'),
'cars' => array('Autos','voitures','macchine'),
);
$langId = 0;
$pattern = "/\{\{[a-zA-Z]+\}\}/";
for($t=0; $t<count($r); $t++) {
$row = $r[$t];
if(!is_array($row))
continue;
foreach($row as $key=>$value) {
if(preg_match_all($pattern, $value, $match, PREG_SET_ORDER)) {
for($i = 0; $i < count($match); $i++) {
//remove {{ & }} to get key
$k = substr($match[$i][0], 2, strlen($match[$i][0])-4);
$replacer = $translations[$k][$langId];
$value = str_replace($match[$i][0], $replacer, $value);
$r[$t][$key] = $value;
}
}
}
}
?>
I'm trying to get sum and average of visitors from the following multi-dimensional array :
Array([visitors] => Array(
[2015-06-12] => Array([0] => Array([value] => 29))
[2015-06-11] => Array([0] => Array([value] => 55))
...
))
I cannot manage to find a way to get the results i need as i get lost with "foreach".
Can anybody help please ?
Use this
<?php
$mainarray = array('visitors' => Array(
'2015-06-12' => Array(Array('value' => 29)),
'2015-06-11' => Array(Array('value' => 55))));
$sum = 0;
$count = 0;
$visitor = $mainarray['visitors'];
foreach ($visitor as $key => $val) {
$sum += $val[0]['value'];
$count++;
}
echo "Sum is " . $sum."<br>";
$average = ($sum / $count);
echo "Average is " .$average."<br>";;
?>
I expect array_combine to be able to take two arrays such as:
array('sample', 'sample_two', 'sample');
array(array('info', 'info_two'), array('bananas'), array('more_stuff'));
and produce:
array(
'sample' => array(
'info', 'info_two', 'more_stuff'
),
'sample_two' => array(
'bananas'
)
);
instead I get:
array(
'sample' => array(
'more_stuff'
),
'sample_two' => array(
'bananas'
)
);
Now I know php doesn't allow for duplicate key's so how can I use array_combine or some other method to achieve the desired array? It is safe to say that, the first array, will always match the second array in terms of layout. So you can draw lines between the values of array one and array two.
Why not writing your own function?
function my_array_combine(array $keys, array $values) {
$result = array();
for ($i = 0; $i < count($keys); $i++) {
$key = $keys[$i];
if (!isset($result[$key])) {
$result[$key] = array();
}
$result[$key] = array_merge($result[$key], $values[$i]);
}
return $result;
}
I need to assign in an associative array a number as key name, but if I do:
// Places (generated by mysql)
$places = array (
0 => '1234',
1 => '2345'
);
// Week stats (generated by mysql)
$week = array (
1234 =>
array (
0 =>
array (
'iid' => '1234',
'mid' => 'xxxxxxxx',
'name' => 'Name1',
),
1 =>
array (
'iid' => '1234',
'mid' => 'xxxxxxxx',
'name' => 'Name3',
)
),
2345 =>
array (
0 =>
array (
'iid' => '2345',
'mid' => 'xxxxxxxx',
'name' => 'Name2',
),
2 =>
array (
'iid' => '2345',
'mid' => 'xxxxxxxx',
'name' => 'Name4',
)
)
);
foreach($places as &$place) {
echo $place;
$i = 0;
foreach($week[$i] as &$value) {
echo $value["name"];
$i++;
}
}
it doesn't work:
http://codepad.viper-7.com/Y1g37t
because seems I should call it with:
echo $arr[<specific index>];
Instead I need to set "1234" and "2345" as strings, like this array:
$arr = Array("foo" => "bar");
So I can call it with
$arr[0] // bar
How can I do?
Solution
Thanks to #kirilloid
i use this code:
$vararr = array_keys($week);
$key = $vararr[$i];
To get the key
It because it's an map and map associates values to keys so you have to do this :
<?php
$myNumber = 1234;
$myValue = "foo";
$arr = Array( $myNumber => $myValue );
echo $arr[1234];
?>
And don't forget to replace the ":" at your first line !
To iterate on a "map" you can use the foreach function :
foreach($arr as $key=>$value) {
echo $key;
echo $value;
}
This should display your key and the value associated :
1234
foo
Here is the difference with a simple array:
$array = array("foo", "bar", "hallo", "world");
echo $array[0];
You may either use array_keys:
echo $arr[array_keys($arr)[0]];
or reset and current:
reset($arr);
echo current($arr);
There is no problem here - this is how it is supposed to work.
If you create an array like this:
$myNumber = 1234;
$myValue = "foo";
$arr = Array( $myNumber => $myValue );
then the index of the element is 1234, not 0.
You can retrieve it with echo $arr[1234]
If you need to loop over the array you can do so with
foreach($arr as $key=>$value) {
// do something with $value
}
There is no problem. As the value of $myNumber is 1234, you should access the array element like this:
echo $arr[1234];
If you need to access them in a foor loop you can get the keys as an array:
$keys = array_keys($arr);
$keys_count = count($keys);
for ($i=0; i<$keys_count; $i++) {
echo $arr[$keys[$i]];
}