I have two array:
$one = Array
(
[0] => stdClass Object
(
[id] => 2
[name] => Southampton
)
[1] => stdClass Object
(
[id] => 4
[name] => Manchester United F.C
)
)
and
$two = Array
(
[0] => stdClass Object
(
[number] => 25555
[slice_1] => 4
[slice_2] => 4
[slice_3] => 2
[slice_4] => 4
[status] => Published
)
)
I want to output, if array $two->slice_1 same as array $one->id than output $one->name.
For example:
$two[0]->slice_1 (4) compare to $one[0]->id (4) will result in Manchester United F.C.
Because the array $one and $two will be have more than one array. Please don't answer this:
if($two[0]->slice_1 == $one[1]->id){echo $one[0]->name;}
I'm stucking here and can't think out some way. Please help. Thanks in advance
avoiding loops inside loops first create temp reference array then loop though second array outputting the result
foreach($one as $id=>$data){
$temp[$data['id']] = $data['name'];
}
foreach($two as $secondary_id=>$secondary_data){
echo isset($temp[$secondary_data['slice_1']]) ? $temp[$secondary_data['slice_1']] : '';
}
Related
I have three arrays first array include ids and employees name and second array have monthly collection with employee ids and third array have daily collection with employee id and daily collection I want to merge these array with ids and name and dcollection and monthly collection but the desired output is not coming here my first array $ids is
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Rohit
)
[1] => stdClass Object
(
[id] => 2
[name] => Emop1
)
[2] => stdClass Object
(
[id] => 3
[name] => Pankaj
)
[3] => stdClass Object
(
[id] => 4
[name] => tejpal singh
)
)
second array $q1 is
Array
(
[0] => stdClass Object
(
[name] => Rohit
[id] => 1
[mcollecton] => 100
)
[1] => stdClass Object
(
[name] => Emop1
[id] => 2
[mcollecton] => 1222
)
)
third array $q2 is
Array
(
[0] => stdClass Object
(
[name] => Rohit
[id] => 1
[dcollecton] => 300
)
[1] => stdClass Object
(
[name] => Emop1
[id] => 2
[dcollecton] => 150
)
)
so far what I have tried
$new_array = array();
foreach($ids as $k) {
$q1n = array("id"=>$k->id,"name"=>$k->name);
foreach($q1 as $k1) {
if($k->id==$k1->id){
$mc = array("mc"=>$k1->mcollecton);
array_merge($q1n,$mc);
}
}
foreach($q2 as $k1){
if($k->id==$k1->id){
$dc = array("dc"=>$k1->dcollecton);
array_merge($q1n,$dc);
}
}
$a = array_merge($q1n,$mc);
$av = array_merge($q1n,$dc);
array_push($new_array,$q1n);
}
but the output is coming as
Array
(
[0] => Array
(
[id] => 1
[name] => Rohit
)
[1] => Array
(
[id] => 2
[name] => Emop1
)
[2] => Array
(
[id] => 3
[name] => Pankaj
)
[3] => Array
(
[id] => 4
[name] => tejpal singh
)
)
I want the output be like
Array
(
[0] => Array
(
[id] => 1
[name] => Rohit
[mcollection] => 100
[dcollection] => 300
)
[1] => Array
(
[id] => 2
[name] => Emop1
[mcollection] => 1222
[dcollection] => 150
)
[2] => Array
(
[id] => 3
[name] => Pankaj
[mcollection] => 0
[dcollection] => 0
)
[3] => Array
(
[id] => 4
[name] => tejpal singh
[mcollection] => 0
[dcollection] => 0
)
)
So I have tried many times but the desired output is not coming . please help me out how to get the desired output.
It seemed like that answer could be modified, or put in a function that you could call multiple times if needed to combine more than two arrays.
There's probably cleaner ways to handle this with array functions like array_merge or array_walk, but this is the general idea of how I might approach it. I haven't tested this, but maybe it's useful.
foreach($first as $key1 => $value){
foreach($second as $key2 => $value2){
// match the ids and check if array key exists on first array
if($value['id'] === $value2['id'] && empty($first[$key2])){
$first[$key][$key2] = $value2;
}
}
}
EDIT: Based on the answer you posted vs the question you asked, are you incrementing the collection numbers or just setting them? In other words why use +=? You should also be able to remove array_merge and array_push.
Below is geared more towards what you're trying to do. I haven't tested this either, but if you run into errors, post your code with the errors returned so that it's easier to debug:
foreach($ids as $k)
{
$thisArray = $newArray[] = array("id"=>$k->id,"name"=>$k->name);
foreach($q1 as $k1)
{
if($k->id == $k1->id && !empty($k1->mcollecton))
{
$thisArray['mc'] = $k1->mcollecton;
}
}
foreach($q2 as $k2)
{
if($k->id == $k2->id && !empty($k2->dcollecton))
{
$thisArray['dc'] = $k2->dcollecton;
}
}
}
// This should have both new collections fields on all array items
print_r($newArray)
I'm about using CodeIgniter for my first project. I have tried to get data from database.
$test = $this->komponen_model->get_participants_id()->result_array();
print_r($test)
Array (
[0] => Array ( [id] => 1 )
[1] => Array ( [id] => 4 )
[2] => Array ( [id] => 7 )
)
And I got this. So, I need to call each element by:
foreach ($test as $ts){
echo $ts['id'];
}
My question is, can I make the array shorten. Just like:
Array (
[0] => 1
[1] => 4
[2] => 7
)
I will be appreciated for anyone's advise.
Use array_column
$test = array_column($test,'id');
foreach ($test as $ts){
echo $ts;
}
$summary=$query->result_array(); //where the original array is created
print_r($summary); //dump contents
Produces this:
Array ( [0] => Array ( [RecordID] => 2 [UserID] => 3 [BookID] => 1 [Title] => FirstBook ) [1] => Array ( [RecordID] => 3 [UserID] => 3 [BookID] => 2 [Title] => Sequel ) )
I would now like to pad the multi dimensional array with a price element so as to create the results of
Array ( [0] => Array ( [RecordID] => 2 [UserID] => 3 [BookID] => 1 [Title] => FirstBook [Price] => 99 ) [1] => Array ( [RecordID] => 3 [UserID] => 3 [BookID] => 2 [Title] => Sequel [Price] => 99) )
The only way I can think of doing this is to break the multidimensional array into one-dimensional arrays, modify them, and then re-assemble them. Doesn't sound terribly efficient though. Any suggestions?
You can update the internal arrays by reference, note the & here:
foreach($summary as &$details){
$details['Price'] = $price; // wherever $price comes from...
}
try to use:
foreach ($summary as $idx => &$arrValue)
$arrValue['Price'] = ###;
If you're fixed on your dimensions, iterate with a reference and modify $summary in place...
<?php
foreach ($summary as &item) {
$item['price'] = 99;
}
If you have particular objections/issues with references:
<?php
foreach ($summary as $key=>item) {
$summary[$key]['price'] = 99;
}
I want to compare two tabdelimeted files. I take the files and converts them into two arrays with the following structure:
Array 1
Array
(
[0] => Array
(
[name] => name1
[qty] => 200
)
[1] => Array
(
[name] => name2
[qty] => 9
)
[2] => Array
(
[name] => name3
[qty] => 3
)
[3] => Array
(
[name] => name4
[qty] => 1
)
)
Array 2
Array
(
[0] => Array
(
[name] => name1
[qty] => 180
)
[1] => Array
(
[name] => name2
[qty] => 9
)
)
How can I compare these two arrays and where the value is different to replace the value in the array 2 with array of value 1.
The easiest way to do this would be to create an associative array for the second set of data, instead of the array format you has used above. Since you only seem to have two "columns", and these are effectively a key/value relationship this should be nice and easy.
This example takes the two input arrays you have generated to do it, but you can probably adjust this so that you create the associative array directly as you read the second:
// first create an associative array from the second indexed array
$secondAssoc = array();
foreach ($secondArray as $row) {
$secondAssoc[$row['name']] = $row['qty'];
}
/*
$secondAssoc now looks like:
Array
(
[name1] => 180
[name2] => 9
)
*/
// Now loop the first array and update it
foreach ($firstArray as $rowId => $row) {
if (isset($secondAssoc[$row['name']]) && $secondAssoc[$row['name']] != $row['qty']) {
$firstArray[$rowId]['qty'] = $secondAssoc[$row['name']];
}
}
/*
$firstArray now looks like this:
Array
(
[0] => Array
(
[name] => name1
[qty] => 180
)
[1] => Array
(
[name] => name2
[qty] => 9
)
[2] => Array
(
[name] => name3
[qty] => 3
)
[3] => Array
(
[name] => name4
[qty] => 1
)
)
*/
See it working.
EDIT Here is a version that also creates an array, $modifiedItems, that holds only the items that have changed:
// first create an associative array from the second indexed array
$secondAssoc = array();
foreach ($secondArray as $row) {
$secondAssoc[$row['name']] = $row['qty'];
}
// Now loop the first array and update it
$modifiedItems = array();
foreach ($firstArray as $rowId => $row) {
if (isset($secondAssoc[$row['name']]) && $secondAssoc[$row['name']] != $row['qty']) {
$firstArray[$rowId]['qty'] = $secondAssoc[$row['name']];
$modifiedItems[] = array('name'=>$row['name'],'qty'=>$secondAssoc[$row['name']]);
}
}
See it working.
Basically I have a setup like the following:
Array (
[0] => Array ( [0] => stdClass Object ( [nid] => 1 [title] => title1 [uid] => 1 [parent] => 0 [weight] => -15 [name] => name1 [value] => 0 )
[1] => stdClass Object ( [nid] => 2 [title] => title2 [uid] => 1 [parent] => 0 [weight] => -7 [name] => name2 [value] => 100 )
[2] => stdClass Object ( [nid] => 3 [title] => title3 [uid] => 2 [parent] => 0 [weight] => -1 [name] => name3 [value] => 0 )
[3] => stdClass Object ( [nid] => 4 [title] => title4 [uid] => 2 [parent] => 0 [weight] => 1 [name] => name4 [value] => 80 )
)
)
What I need is a way to sort all the arrays inside the parent array by the [value] key in the Object. I've been trying for about 2 days now with usort and different methods but I just can't seem to get my head around it. The [value] key will range anywhere from 0 to 100 and I need all of the arrays sorted in decreasing order (IE: 100 down to 0).
Use usort:
function cmp($a, $b) {
if ($a->value == $b->value) {
return 0;
} else {
return $a->value < $b->value ? 1 : -1; // reverse order
}
}
usort($arr, 'cmp');
100% stolen from the 1st answer on this page.
http://us.php.net/manual/en/function.array-multisort.php
But this is what I was looking for.
multisort an Array of Objects:
example object [$object with array of objects]: (class: test)
----------------------------------
test Object (
[Artikel] => Array (
[0] => test Object (
[id] => 1
[title] => CCCC
)
[1] => test Object (
[id] => 2
[title] => AAAA
)
[2] => test Object (
[id] => 3
[title] => DDDD
)
[3] => test Object (
[id] => 4
[title] => BBBB
)
)
)
----------------------------------
Simple PHP function: sort_arr_of_obj()
<?php
// --------------------------------------
/*
* -------- function arguments --------
* $array ........ array of objects
* $sortby ....... the object-key to sort by
* $direction ... 'asc' = ascending
* --------
*/
function sort_arr_of_obj($array, $sortby, $direction='asc') {
$sortedArr = array();
$tmp_Array = array();
foreach($array as $k => $v) {
$tmp_Array[] = strtolower($v->$sortby);
}
if($direction=='asc'){
asort($tmp_Array);
}else{
arsort($tmp_Array);
}
foreach($tmp_Array as $k=>$tmp){
$sortedArr[] = $array[$k];
}
return $sortedArr;
}
// --------------------------------------
?>
example call:
----------------------------------
<?php
$sorted->Artikel = sort_arr_of_obj($object->Artikel,'title','asc');
?>
example result: $sorted (class: test)
----------------------------------
test Object (
[Artikel] => Array (
[0] => test Object (
[id] => 2
[title] => AAAA
)
[1] => test Object (
[id] => 4
[title] => BBBB
)
[2] => test Object (
[id] => 1
[title] => CCCC
)
[3] => test Object (
[id] => 3
[title] => DDDD
)
)
)
A way to do this is to separate the value array from the array of objects, and thus, creating two arrays. You can then use array_multisort to sort the array of objects according to the other array. Here's an example:
<?php
$array1 = $objectvalues
$array2 = array(ObjectWithNid1, ObjectWithNid2, ObjectWithNid3, ObjectWithNid4);
array_multisort($array1, $array2);
?>
You can use a foreach to loop the array one time and create a new array with the corresponding [value] key:
<?php
foreach( $arraywithobjects as $obj )
{
$objectvalues[] = $obj->getValue();
}
?>
This will get the Object's value and insert it into another array which you can use with the multisort.
In the end, your code will look like this:
<?php
foreach( $arraywithobjects as $obj )
{
$objectvalues[] = $obj->getValue();
}
$array2 = array(ObjectWithNid1, ObjectWithNid2, ObjectWithNid3, ObjectWithNid4);
array_multisort($objectvalues, $array2);
?>
The first array in the array_multisort field should be the array you're using to sort the second array.
You can also add other sorting method for this. You can read them here: link text
function cmp($a, $b) {
return $b->value - $a->value;
}
$ary[0] = usort($ary[0], "cmp");
In order to sort an array based on anything other than simple value or key, you need to use the usort function and supply your own comparison. Comparison functions must be defined such that if $a comes before $b, a positive value is returned and a negative one if $b comes before $a (or zero if they are equal). As you are comparing based on number values and you want a reverse sort, the simplest way of doing this is to subtract the 'value' of $a from the value of $b.
I could be wrong, but I believe I did something like this using asort() (or asort()). It was in a search function, where I needed to sort a two-dimensional array filled with indices and timestamps.
I'm not sure if it will work in your case, and I did it long ago. Maybe it will get you started though, good luck.