I was wondering how to use array_push to multidimensional arrays?
I have a multidimensional array, in which i'm trying to push more values from another array. The multidimensional you can see below.
$userList[] = array(
"aid" => $searchrow['aid'],
"name" => $searchrow['name'],
"info" => $searchrow['info'],
"rental" => $searchrow['rental'],
"rentalfirm" => $searchrow['rental_firm'],
"acqprice" => $searchrow['acq_price'],
"renprice" => $searchrow['ren_price'],
"serial" => $searchrow['serial']);
}
Second set of arrays:
mysql query... blaa blaa
$assetInuseID[]=$searchrowinuse['asset_usage_id'];
$inuse[]=$searchrowinuse['in_use'];
$total[]=$searchrowinuse['total'];
What I'm tryin to accomplice is something like below.
$i = 0;
while(!empty($userList[$i][aid]))
{
if($userList[$i][aid] == $assetInuseID[$i])
{
array_push($userList[$i][inUse], "$inuse[$i]");
array_push($userList[$i][total], "$total[$i]");
}
$i ++;
}
So, I want to create: inUse- and total-cells in the allready existing $userList[][] and populate them with with the allready existing values of $total[$i] and $inuse[$i] when the $userList[$i][aid] matches $assetInuseID[$i].
I hope someone understands me, my explanation was a little bit confusing...
Thank you very much.
You can use the following,
$userList[$i]["inUse"] = "$inuse[$i]";
Remember array_push — Push one or more elements onto the end of array and not create an index.
Related
I have those two arrays that I added to attachments.
"PartnerAffiliateCodeId" from first array and "Id" from second array is our primary key.
"UserAction" must be counted for every unique "PartnerAffiliateCodeId" so in our case it is 5.
Normally I think this must be done by SQL but unfortunately this is a API method that I am receiving so I have to handle it by PHP.
Any ideas about how I can make such join with PHP using these two arrays?
I'm unclear on exactly what you're trying to get at with UserAction, but you could try something like this:
//$array1 = the first array
//$array2 = the second array
array_push($array_1, array(
"DateTime" => "",
"HttpReferer" => "",
"Id" => count($array1),
"PartnerAffiliateCodeId" => $array2["Id"],
"UserAction" => "Click"
));
It sounds like you want to match the ID key to the PartnerAffiliateCodeId in your returned data set.
Without knowing your setup, or bothinging with total optimization here a workable solution which will give you some direction.
function selectPartnerWhere($id=null; $from=array())
{
$codes = array();
foreach($from as $k => $p)
{
if($id == $p['PartnerAffiliateCodeId'])
{
return $from[$k];
}
}
return array();
}
$theData = //your array above
$thePartner = //your partner above
$partnerData = selectPartnerWhere($thePartner['Id'], $theData);
This question already has answers here:
How to search by key=>value in a multidimensional array in PHP
(17 answers)
Closed 9 years ago.
What would be the most efficient way of looking at an array of associative arrays, to find the node which meets a parameter?
I would like to have a more efficient way of looking through the array to find and return the parent node, that just looping through - looking at each element and returning if matched. (it is also safe to assume, that there are no duplicates of data - so the first found, is the only one found)
Or is a for loop the best thing ive got?
e.g.
array(
[0] => array('name' => 'fred'),
[1] => array('name' => 'dave'),
[2] => array('name' => 'mike)
)
And wanting to get the node of data where the name == 'dave' or to see if there is in fact a node which has a element name set as 'dave'.
e.g. somthing like
isset($data[]['name'] == 'dave')
$info = getdata($data[]['name'] == 'dave')
(Apologies if I'm not using the correct technical terms, please do correct me as I do like to learn!)
Many thanks in advance for any advice! =)
There is no better way than looping. PHP can't perform any magic that does not involve looking at each element in turn.
If you're doing this often, it helps to index your arrays by the search criterion:
$data = array(
array('name' => 'Dave'),
array('name' => ...)
);
$indexedData = array();
foreach ($data as $datum) {
$indexedData[$datum['name']] = $datum;
}
$info = $indexedData['Dave'];
As long as your data structure is sub-optimal, there's only sub-optimal ways to access it.
Here's a function for array recursion to one level. We use foreach() to loop through each second layer of child arrays, then use the built-in function array_search to see if it exists.
function as_nested($needle,$haystack){
$val;
foreach($haystack as $key=>$arr){
$arr_key = array_search($needle,$haystack[$key]);
if(!empty($arr_key)){
$val = $key;
}
}
return $val;
}
To execute, you supply the needle, then the haystack.
echo as_nested('dave',$myArray);
Output using your initial array is 1.
$myArray[0] = array('name'=>'fred');
$myArray[1] = array('name' => 'dave');
$myArray[2] = array('name' => 'mike');
There is a function in php called in_array() that looks for a value in an array.
//Code credit to #deceze
$data = array(
array('name' => 'Dave'),
array('name' => ...)
);
function getData($data, $searchValue) {
foreach ($data as $datum) {
if (in_array($searchValue, $datum)) {
return $datum;
}
}
//array returned when $searchValue is found.
You can use the getData function to search for a value in an array (this is not index specific. ie not restricted by only name, etc.)
I have fields in mySQL which is currently being stored like this under the field "tags"
Shopping|Health & Beauty
Coffee|Shopping
What I'm trying to do is to loop through this to create a single dimension array and to grab only the unique values.
I have my query selecting DISTINCT tags from TABLE and run the loop like this:
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$imploded_tags[] = explode("|",$tags);
}
echo "<pre>";
print_r($imploded_tags);
The result from the print_r is showing it as a multidimensional array. I've tried to reexplode it and implode it in different ways, but I haven't been able to get any success. Is there a way that I can create this into a single dimension array? Not all tags will have an equal amount of tags separated by |, so I can't seem to get it to go with a function that I tried from another StackOverflow post. Any help would be greatly appreciated!
OUTPUT:
Array
(
[0] => Array
(
[0] => Shopping
[1] => Health & Beauty
)
[1] => Array
(
[0] => Coffee
[1] => Shopping
)
try this
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$tags = explode("|",$tags);
foreach($tags as $v){
$imploded_tags[] = $v;
}
}
I would do something like:
$imploded_tags = array_merge(explode("|",$tags), $imploded_tags);
}
$imploded_tags = array_unique($imploded_tags);
echo "<pre>";
print_r($imploded_tags);
See the manual on array_merge and array_unique.
However, I do think you are not using the right way to store your tags; they should be stored in a separate table as separate values.
What's going on is when you're fetching your rows from MySQL, you're essentially getting a bunch of data in an array in the first place, which is why you have to loop through them.
With your your implode function, you're taking a bunch of strings, then getting another array set and then appending that to an external array.
If you really wanted to get a single dimensional array without having this multidimensional thing going on, all you really need to do is utilize another loop within that loop.
$all_tags = array();
while ($row_tags = mysql_fetch_assoc($r_tags)) {
$tags = $row_tags['tags'];
$imploded_tags[] = explode("|",$tags);
for($i = 0; $i < count($imploded_tags); $i++) {
$all_tags[] = $imploded_tags[$i]
}
}
print_r($all_tags);
I am attempting to generate a multi-dimensional array with each sub array representing a row I want to insert into my DB. The reason for this is so I can use CodeIgniters batch_insert function to add each row to the DB.
I am attempting to create each sub array within a loop and insert it into a multidimensional array. Google suggested using array_merge, but after using 'print_r' on the multidimensional array with the code below, only the last sub-array is being displayed.
Here is my code:
$allplayerdata = array(); //M-D container array
for ($i = 1; $i <= 11; $i++)
{
$playerdata = array(
'player_id' => $this->input->post('player' . $i),
'goals' => $this->input->post('playergoals' . $i),
'player_num' => $i,
'fixture_id' => $this->input->post('fixture_id')
);
//Merge each player row into same array to allow for batch insert
$allplayerdata = array_merge($allplayerdata, $playerdata);
}
print_r($allplayerdata);
Can anyone spot where I'm going wrong? Help is appreciated!
This is because array_merge is not the right operation for this situation. Since all the $playerdata arrays have the same keys, the values are overridden.
You want to use array_push to append to an array. This way you will get an array of $playerdata arrays.
array_push($allplayerdata, $playerdata);
Which is equivalent to adding an element with the square bracket syntax
$allplayerdata[] = $playerdata;
array_merge - Merge one or more arrays
array_push - Push one or more elements onto the end of array
Creating/modifying with square bracket syntax
This will add the second array to the first array: A merge is something different.
$allplayerdata[] = $playerdata;
I have this array:-
Array ( [0] => Prefectorial Board/Prefect/2011 [1] => Prefectorial Board/Head Prefect/2011 [2] => Class Positions/Head Prefect/2011 [3] => Prefectorial Board/Head Prefect/2011 )
How to detect this array have duplicate value and I want the participant to re-fill in his data.
I have try to use this method to detect:-
$max = max(array_values($lr_str));
$keys = array_keys($lr_str, $max);
but it seem like not work for me.
any idea on this?
thanks for advance.
I do not know if I understand you correctly, but you can test the array has duplicated values by using this:
if (count($your_array) === count(array_unique($your_array)) {
// array has no duplicated values
} else {
// array has duplicated values - see compared arrays
}
Are you looking for array_unique?
You can use array_unique() to remove duplicate values. If no values were removed then the returned array should have the same number of items as the original:
if(count($lr_str) == count(array_unique($lr_str))){
//tell participant to re=fill their data
}