Trying to do multidimentional array in PHP but something going wrong - php

I have an array that I declare like this:
$health_array = array( );
For every iteration I try to put these 3 items in it like this:
$health_array["num_problems"] = $num_problems;
$health_array["category_id"] = $category_id;
$health_array["category_name"] = $category_name;
But when I loop through the array I get gibberish. Here is how I loop through it:
foreach ($health_array as $i => $row)
{
echo '<p>'.$row['category_name'].' '.$row['category_id'].' '.$row['num_problems'].'</p>';
}
Any idea what I am doing wrong?
Thanks!!

Your problem comes from the fact that you want to do a multi-dimensional array and you're creating a monodimensional one, by overwriting each time the same 3 elements.
You should do something like:
$health_array = array();
$tmp = array();
$tmp["num_problems"] = 5;
$tmp["category_id"] = 8;
$tmp["category_name"] = "something";
$health_array[] = $tmp;
$tmp["num_problems"] = 15;
$tmp["category_id"] = 22;
$tmp["category_name"] = "something else";
$health_array[] = $tmp;
foreach ($health_array as $h)
{
echo $h["num_problems"]." - ".$h["category_id"]." - ".$h["category_name"]."<br />";
}

For every iteration I try to put these 3 items in it like this:
$health_array["num_problems"] = $num_problems;
$health_array["category_id"] = $category_id;
$health_array["category_name"] = $category_name;
It looks like you meant to build your array like this instead:
$health_array[] = array(
"num_problems" => $num_problems,
"category_id" => $category_id,
"category_name" => $category_name
);
This makes an array of arrays, where previously you were overwriting the keys of the same array for each iteration.

Related

Select one item from array

So, I wanna select item per item from this array ["A185","A740","A540"]
Like for example I wanna select
$cie[0] = A185 or A740
with something like $cie[0] = A185
This is my code so far, since I fetch that code from a row in a MySQL table.
while ($row = pg_fetch_array($resul)) {
$cie10 = array($row["cie"]);
}
$cie = ["A185","A740"];
$values = array_count_values($cie);
$top = array_slice($values, 0, 1);
print_r($top);
What I get:
Array ( [["A185","A740","A540"]] => 1 )
It just won't work.
I'm Sure you are looking to display the data that is in the array variable
$var = ["A185","A740","A540"]; // Asume as you stored the values in the array called var
foreach($var as $x){
print_r($x);
echo "<br/>";
}
EDIT: Highlighted the code
If i understand your problem. You are looking for this:-
$Fullarray = ["A185","A740","A540"];
$cie = array_slice($Fullarray,0,2);
foreach ($cie as $name) {
$d[] = '"' . $name . '"';
}
$implodekeys = "[".implode(',',$d)."]";
$newarray[$implodekeys] =1;
echo "<pre>"; print_r($newarray);
Hope it helps!

PHP return second value of 2D array

I have the following PHP code:
$special_files = array(
array("Turnip", "Tweed"),
array("Donald", "Trump")
);
I want to be able to get the second value in a nested array by identifying a first. eg: if_exists("Donald") would return "trump".
I've tried to recurse through the array but I'm at a loss on how to select the second value once the first is identified.
Any help would be appreciated
You can use something like this:
$special_files = array(
array("Turnip", "Tweed"),
array("Donald", "Trump")
);
$search_val = "Donald";
$key = array_search($search_val, array_column($special_files,0));
$output = $special_files[$key][1]; //outputs "Trump"
Here is a working sample.
Well, you can try the following:
foreach ($special_files as $special_file) {
$i = 1;
foreach ($special_file as $element) {
if ($i==2) {
echo ("Second value is: " . $element);
break;
}
$i++;
}
}
You can extract the [1] elements and index them by the [0] elements:
$lookup = array_column($special_files, 1, 0);
$result = isset($lookup['Donald']) ?: false;
The $lookup array yields:
Array
(
[Turnip] => Tweed
[Donald] => Trump
)

Create new array from existing array in php

Good Day
I have an array containing data seperated by a comma:
array (
[0]=>Jack,140101d,10
[1]=>Jack,140101a,15
[2]=>Jack,140101n,20
[3]=>Jane,141212d,20
[4]=>Jane,141212a,25
[5]=>Jane,141212n,30
)
There is a lot of data and I would like the data to be set out as:
array(
[Jack]=>
[140101]
=>[d] =>10
=>[a] =>15
=>[n] =>20
)
My code:
foreach ($out as $datavalue) {
$dat = str_getcsv($datavalue,',');
$datevalue = substr($dat[1],2,-1);
$shiftvalue = substr($dat[1],-1);
$totalvalue = $dat[2];
$sval[$shiftvalue] = $totalvalue;
$dval[$datevalue] = $sval;
$opvalue = $dat[0];
$final[$opvalue] = $dval;
}
Now it seems the array is populated even if there is no data from the original string, so my output shows results for Jack on the other dates even though there was no data for him originally. Hope this makes sense. Could anyone point out or suggest a solution please?
As mentioned in the comments, explode is what you need. See this working here.
<?php
$input = array (
0 => 'Jack,140101d,10',
1 => 'Jack,140101a,15',
2 => 'Jack,140101n,20',
3 => 'Jane,141212d,20',
4 => 'Jane,141212a,25',
5 => 'Jane,141212n,30',
);
$result = array();
foreach ($input as $key => $value) {
$valueParts = explode(',',$value); // now valueparts is an array like ('Jack','140101d','10')
$namePart = $valueParts[0];
$idPart = substr($valueParts[1],0,-1); // we need to strip the letter from the id
$charPart = substr($valueParts[1],-1); // and the id from the letter
$nrPart = $valueParts[2]; // you could use intval() to make this an integer rather than a string if you want
// Now we fill the array
if(!array_key_exists($namePart, $result)) {
$result[$namePart] = array();
}
if(!array_key_exists($idPart, $result[$namePart])) {
$result[$namePart][$idPart] = array();
}
if(!array_key_exists($charPart, $result[$namePart][$idPart])) {
$result[$namePart][$idPart][$charPart] = $nrPart;
}
}
var_dump($result);

Dynamic Array with PHP

Post Updated
I would like to create dynamic Array in PHP to provide the same output like static Array below, I have tried to do it with while statement but it doesn't work. Could you please provide me some tips?
I would like to use 2 values from MySQL and save them in to $to variable
so first send_to1 (user account) and then value1 (amount)
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM users");
$to=Array(
while($row = mysqli_fetch_array($result))
{
$send_to1 => $value1,
$send_to2=> $value2
}
);
mysqli_close($con);
?>
It's as simple as just adding elements to the array:
//Setup blank array
$example = array();
//Create a loop, for example purposes.
foreach(range(0, 99) as $i){
//Create random variable that we'll add to our array
$randVar = mt_rand(1, 90000);
//$i will be our array key/index
$example[$i] = randVar;
}
//var_dump the array so you can see the structure / end result
var_dump($example);
You could also create it like so:
//Create random array key/index
$myRandKey = mt_rand(1, 90000);
//Create random variable value.
$myRandVar = mt_rand(1, 90000);
//Setup an array
$example = array(
$myRandKey => $myRandVar
);
//Another array key that we'll add to our array
$secondKey = 'test';
//Add it
$example[$secondKey] = 'This is just an example!';
//Dump out the array
var_dump($example);
array_push will also work (using mysql_fetch_assoc, like in your example):
$example = array();
while($row = mysql_fetch_assoc($result)){
array_push($example, $row);
}
var_dump($example);
In your particular example (since you added your code):
print_r($new_array[] = $row[]);
should be changed to:
print_r($new_array[] = $row);
In your code, I'd change it to:
$new_array = array();
while($row = mysqli_fetch_array($result)){
$new_array[] = $row;
}
Or, if you want to key your array by a unique column (Primary key, for example):
$new_array = array();
while($row = mysqli_fetch_array($result)){
$new_array[$row['id']] = $row;
}
Look, this is so easy, you just need to pay more attention to the answers you're getting here.
Here is the simplest way you can do it:
$to = array();
$to[] = array($send_to1 => $value1);
$to[] = array($send_to2 => $value2);
while ( $row = mysqli_fetch_array($result) ) {
$to[] = array($row['send_tox' => $row['valuex']);
}
You need to first understand how Arrays and Loops work in PHP, then try to make a dynamic array in a loop.
Actually you almost got it. It's lower A in 'array'
To initialize an empty array:
$to = array();
In your case (you already have some values), you can do:
$to = array(
$send_to1 => $value1,
$send_to2=> $value2
);
In either case, you can later add more elements doing
$to[$someOtherKey] = $someOtherValue;

Combining 2 arrays into one

I got 2 arrays:
$ping_array = array();
$ping_array[] = '400';
$ping_array[] = '200';
$ping_array[] = '600';
$ping_array[] = '100';
$timestamp_array = array();
$timestamp_array[] = '2013-03-25 16:30:07';
$timestamp_array[] = '2013-03-25 16:30:39';
$timestamp_array[] = '2013-03-25 18:30:06';
$timestamp_array[] = '2013-03-25 18:45:49';
I want to make something like this (i dont know how its called):
$combined_array = array(
'time' => $timestamp_array,
'ping' => $ping_array
);
so later on i could use the 2 arrays combined like this:
foreach ($combined_array as $ca=> $values) {
echo $values['ping'];
echo $values['time'];
}
Thx guys this combine_array is amazing
Try this:
$combined_array = array();
foreach ($ping_array as $key => $value){
$combined_array[] = array(
'time' => $timestamp_array[$key],
'ping' => $value
);
}
What about this?
for ($i=0; $i<count($timestamp_array); $i++) {
$combined_array[$i]["ping"] = $ping_array[$i];
$combined_array[$i]["time"] = $timestamp_array[$i];
}
PHPs array_combine: "Creates an array by using one array for keys and another for its values"
$combined_array = array_combine($timestamp_array, $ping_array);
Then just repeat through similar to what you included:
foreach($combined_array as $time => $ping) {
echo $ping;
echo $time;
}
How about php 'array_merge_recursive'? It does exactly what you are looking for. It is found on php 4 and up.
What you could do is make array of objects, like this:
class PingInfo {
public $ping;
public $time;
public function PingInfo($ping, $time) {
$this->ping = $ping;
$this->time = $time;
}
}
$pingInfos = array();
$pingInfos[] = new PingInfo('400', '2013-03-25 16:30:07');
$pingInfos[] = new PingInfo('300', '2013-03-25 16:50:13');
You could build it from two array like this:
$pingInfos = array();
for ($i = 0; $i < count($ping_array); $i++)
$pingInfos[] = new PingInfo($ping_array[$i], $timestamp_array[$i]);
Now you can access it like this:
foreach ($pingInfos as $pingInfo) {
echo $pingInfo->ping;
echo $pingInfo->time;
}

Categories