I have a multidimensional array.
$shop = array(
array("appn1", "pub1" ,"pub2" , "pub3"),
array("appn2", "pub1"),
array("appn3", "pub1" ,"pub2")
);
The first item in each array is application number and the rest in each array are the publication numbers. I get the first item(application number) and the last item of each array(latest publication number) like this
$index = count(array_keys($shop));
for($i=0;$i<$index;$i++){
$appln_nr = $shop[$i][0];
echo $appln_nr;
$publn_nr_index = count(array_keys($shop[$i]))-1;
$publn_nr = $shop[$i][$publn_nr_index];
echo $publn_nr;
}
Now I have application number and publication number for each inner array.
I want to create an associative array from the application numbers and publication numbers.
where the key should be the application number and its value is the publication number.
Thanks
EDIT
What I am getting from $shop array
Array
(
[0] => Array
(
[0] => appn1
[1] => pub1
[2] => pub2
[3] => pub3
)
[1] => Array
(
[0] => appn2
[1] => pub1
)
[2] => Array
(
[0] => appn3
[1] => pub1
[2] => pub2
)
)
And this is what I need in my associative array
Array(
"appn1" => "pub3"
"appn2" => "pub1"
"appn3" => "pub2"
)
Finally i understood what you wanted, after your edit XD:
$shop = array(
array("appn1", "pub1" ,"pub2" , "pub3"),
array("appn2", "pub1"),
array("appn3", "pub1" ,"pub2")
);
$shopNew = array();
foreach($shop as $value){
$shopNew[$value[0]] = end($value);
}
// now if you want you can replace $shop and unset $shopNew
$shop = $shopNew;
unset($shopNew);
print_r($shop);
the output is this:
Array (
[appn1] => pub3
[appn2] => pub1
[appn3] => pub2
)
You can try
$shop = array(
array("appn1","pub1","pub2","pub3"),
array("appn2","pub1"),
array("appn3","pub1","pub2")
);
$final = array();
array_map(function ($var) use(&$final) {$final[reset($var)] = end($var);}, $shop);
var_dump($final);
Output
array
'appn1' => string 'pub3' (length=4)
'appn2' => string 'pub1' (length=4)
'appn3' => string 'pub2' (length=4)
You can easily convert your array into a new format by using the first element as key (see reset) and the last element (see end) as value:
foreach($shop as $fl) {
$v[reset($fl)] = end($fl);
}
Result is in $v then.
If you want to transform the array you need to delete each element as well:
foreach($shop as $v => $fl) {
$shop[reset($fl)] = end($fl);
unset($shop[$v]);
}
Result is in $shop then. Unset takes care of removing from the array.
Output in both cases is:
array(3) {
'appn1' =>
string(4) "pub3"
'appn2' =>
string(4) "pub1"
'appn3' =>
string(4) "pub2"
}
try this:
foreach($shop as $k => $v) {
$new_arr[$v[0]] = end($v);
}
It should give you this result,
$new_arr = array(
"appn1" => "pub3",
"appn2" => "pub1",
"appn3" => "pub2"-
);
You can also create like this,
$arrField = [];
$arrField['id'] = '0001';
$arrField["first_name"] ='Demo Test';
print_r($arrField);
print_r($arrField) display output like this.
Array ( [id] => 0001 [first_name] => Demo Test )
Related
I have two arrays- one single and other multi-dimensional.
$abc='["first","second","third","fourth"]';
$def='[{"post_id":"1","postid":"42","tags":["eminem","baby","jordan"]},{"post_id":"3","postid":"38","tags"
:["abc","def","jordan"]},{"post_id":"4","postid":"40","tags":["eminem","baby","first","second","fourth"
]}]';
$ghi=json_decode($def,true);
$jkl=json_decode($abc,true);
echo '<pre>';
print_r($jkl);
echo '</pre>';
echo '<pre>';
print_r($ghi);
echo '</pre>';
And this is what it looks like:
Array
(
[0] => first
[1] => second
[2] => third
[3] => fourth
)
Array
(
[0] => Array
(
[post_id] => 1
[postid] => 42
[tags] => Array
(
[0] => eminem
[1] => baby
[2] => jordan
)
)
[1] => Array
(
[post_id] => 3
[postid] => 38
[tags] => Array
(
[0] => abc
[1] => def
[2] => jordan
)
)
[2] => Array
(
[post_id] => 4
[postid] => 40
[tags] => Array
(
[0] => eminem
[1] => baby
[2] => first
[3] => second
[4] => fourth
)
)
)
What I am trying to do is search for the elements of single-dimensional array inside the sub-array tags present in the multi-dimensional array.
This is my code:
$users = array_unique($jkl);
$array = [];
$i=0;
foreach($users as $user)
{
if (in_array($user, $ghi[$i]['tags']))
{
$newdata = array (
'postId' => $ghi[$i]['postid'],
'tag' => $user
);
array_push($array, $newdata);
}
$i++;
}
But I get the error mentioned as the question title.
What could be the possible reason? Thanks!
You have to iterate through multi-dimensional array and do what you want:-
<?php
$abc='["first","second","third","fourth"]';
$def='[{"post_id":"1","postid":"42","tags":["eminem","baby","jordan"]},{"post_id":"3","postid":"38","tags"
:["abc","def","jordan"]},{"post_id":"4","postid":"40","tags":["eminem","baby","first","second","fourth"
]}]';
$ghi=json_decode($def,true);
$jkl=json_decode($abc,true);
$users = array_unique($jkl);
$array = []; // empty array
foreach($ghi as $gh) // iterate through multi-dimensional array not single one
{
for($i=0;$i<count($users);$i++){ // a for loop to iterate through single-dimensional completly
if (in_array($users[$i],$gh['tags'])) // if single dimensional array value exist in multi-dimensional tags array
{
$newdata = array (
'postId' => $gh['postid'],
'tag' => $users[$i]
);
array_push($array, $newdata); // push the data
}
}
}
echo "<pre/>";print_r($array); // print newly created array
?>
Output:-https://eval.in/602523
Note:- Try to put variable name in such a way that they don't produce ambiguity.Thanks
Your both array has different numbers of elements. first array has four elements while second array has three elements. that's why you are getting problem.
You should check variable is set and must be an array. Use !empty() and is_array()
foreach($users as $k=>$user){
if(!empty($ghi[$k]['tags']) && is_array($ghi[$k]['tags'])) { // check this condition here
if (in_array($user, $ghi[$k]['tags'])){
$newdata = array (
'postId' => $ghi[$k]['postid'],
'tag' => $user
);
array_push($array, $newdata);
}
}
}
Note:- I have used array key as $k instead of $i
This is because length of your 2 arrays are different, use isset() to remove error:
as 3rd index of your $ghi array does not exist, and its trying to fetch $ghi[3]['tags'] - that's why error is occurring
Try:
foreach($users as $user)
{
if(isset($ghi[$i]['tags'])) { // just add this condition here
if (in_array($user, $ghi[$i]['tags']))
{
$newdata = array (
'postId' => $ghi[$i]['postid'],
'tag' => $user
);
array_push($array, $newdata);
}
}
$i++;
}
It depends on what you are searching for.
If you want to examine ALL of the $users against ALL of the $ghi array then you need to loop over both each time.
foreach($users as $user)
{
for ($i = 0; $i < count($ghi); $i++) {
if (in_array($user, $ghi[$i]['tags']))
{
$newdata = array (
'postId' => $ghi[$i]['postid'],
'tag' => $user
);
array_push($array, $newdata);
}
}
}
This will result in the $newdata consisting of the following
array(2) { ["postId"]=> string(2) "40" ["tag"]=> string(6) "fourth" }
But if you only want to examine the each array against the other once. Then you need to check to make sure you're not going out of bounds.
$ghi only has 3 elements in it.
there are 4 elements in $users.
So you can either loop through the smaller array in your foreach - switch $users -> $ghi
or check inside the foreach loop that $ghi has a valid element at whatever $i is.
D.
I am trying to put content of one array into the same array. Here I have an array $mclass with values such as
Array
(
[0] => stdClass Object
(
[room_id] => 1,3,5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
You can see I have room_id index with 1,3,5 value. Now, I want to explode the room_id and get duplicate of same array index data with change of room_id and push into the array. and finally delete the current array index such as [0]. Here I want the final result as.
Array
(
[0] => stdClass Object
(
[room_id] => 1
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[1] => stdClass Object
(
[room_id] => 3
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[2] => stdClass Object
(
[room_id] => 5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
Here is my code for the same:
if(count($mclass)>0)
{
foreach($mclass as $mclasskey=>$mclass_row)
{
/* Room ID Calculation */
if(isset($mclass[$mclasskey]))
{
$temp_room_id = explode(',',$mclass_row->room_id);
if(count($temp_room_id)>1)
{
foreach($temp_room_id as $trkey=>$tr)
{
if(!in_array($temp_room_id[$trkey], $morning_class_semester))
{
array_push($morning_class_semester,$temp_room_id[$trkey]);
}
}
if(count($morning_class_semester)>0)
{
foreach($morning_class_semester as $mcskey=>$mcs)
{
$index_count = count($new_test);
$test[$index_count] = $mclass[$mclasskey];
$test[$index_count]->room_id = $morning_class_semester[$mcskey];
array_push($new_test,$test[$index_count]);
}
unset($mclass[$mclasskey]);
}
}
}
}
}
The code below does what you're looking for using only arrays. So you'll have to change the array access operators to -> since you're accessing an object. I'd do so, but it would break the example, so I'll leave that up to you.
Code Explained:
Loop through array selecting each subarray (object in your case), explode on the $item('room_id') ... ($item->room_id in your case) ... and create sub arrays, via loop, from that using the data from the original using each key. Remove the original item (which has the combined room_ids) and combine the placeholder and original array.
<?php
//Establish some data to work with
$array = array(
array(
"room_id" => "1,3,5",
"day" => 1,
"class_teacher" => "TEA-2014-2",
"final_exam_date" => "2015-09-21",
));
foreach ($array as $key => $item) {
$placeholder = array();
$ids = explode(',',$item['room_id']);
if (count($ids) > 1) {
foreach ($ids as $id) {
$push = array(
'room_id' => $id,
'day' => $item['day'],
'class_teacher' => $item['class_teacher'],
'final_exam_date' => $item['final_exam_date']
);
array_push($placeholder, $push);
}
$array = array_merge($array, $placeholder);
unset($array[$key]);
}
}
var_dump($array);
?>
Is there a function/method I am unaware of that avoids removal of like keys when the array is flipped. Example below:
Original array:
Array ( [last_modified] => input [published] => input [project_content] => textarea )
With array flip (collision of keys):
Array ( [input] => published [textarea] => project_content )
If you want to preserve your keys, you can have a two dimensional array:
<?php
$arr = array ( 'last_modified' => 'input', 'published' => 'input', 'project_content' => 'textarea' );
$result = array();
foreach($arr as $k => $v) {
if (array_key_exists($v, $result)) {
$result[$v][] = $k;
} else {
$result[$v] = array($k);
}
}
print_r($result);
?>
This will print out:
Array
(
[input] => Array
(
[0] => last_modified
[1] => published
)
[textarea] => Array
(
[0] => project_content
)
)
There is a dead simple way to get all the keys in the array that have the value "input" using the standard function array_keys:
$keys = array_keys($array, "input");
That is all; see it in action.
I'm really sorry to bug you, put I've got a problem that I've been trying to resolve for quite some time now. I've done some research and have found things like array_merge but it doesn't appear to help me.
Anyway, enough waffle. I have a result of a query that looks something like this:
Array
(
[0] => STRINGA
)
Array
(
[0] => STRINGA
[1] => STRINGB
)
Array
(
[0] => STRINGA
[1] => STRINGB
[2] => STRINGC
)
Array
(
[0] => STRINGD
[1] => STRINGC
[2] => STRINGA
[3] => STRINGB
[4] => STRINGE
[5] => STRINGF
)
How can I combine the above into one array so that the result will look more like:
Array
(
[0] => STRINGA
[1] => STRINGB
[2] => STRINGC
[3] => STRINGD
[4] => STRINGE
[5] => STRINGF
)
Duplicates in the original arrays can be ignored as I only need the string to be placed into the new array once.
Any help would be massively appreciated.
Thank you.
EDITED: This is the block of code that brings out the result from the database:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $splitrow) {
if(NULL != $splitrow) {
$therow = explode(';',$splitrow);
}
//print_r retrieves result shown above
print_r($therow);
}
}
$bigarray = array(
array (
0 => 'STRINGA',
),
array (
0 => 'STRINGA',
1 => 'STRINGB',
),
array(
0 => 'STRINGA',
1 => 'STRINGB',
2 => 'STRINGC',
)
);
$result = array_values(
array_unique(
array_merge( $bigarray[0], $bigarray[1], $bigarray[2] )
)
);
// array_merge will put all arrays together, including duplicates
// array_unique removes duplicates
// array_values will sort out the indexes in ascending order (1, 2, 3 etc...)
$bigarray = array();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
foreach($row as $value){
if($value != NULL){
$therow = explode(';',$value);
foreach($therow as $key=>$values){
//push the value into the single array 'bigarray'
array_push($bigarray, $values);
}
}
}
}
//remove duplicates
$uniquearray = array_unique($bigarray);
//reset key values
$indexedarray = array_values($uniquearray);
print_r($indexedarray);
Thanks to all of those that helped, much appreciated!
I'm trying to experiment with array_splice and I get an output like this (from $match)
Array
(
[Keep me Updated] => Array
(
[winner] => winnerl.jpg
[0] => value0.jpg
)
[0] => valuel.jpg //this should really be inside [Leep me Updated] array
[1] => value2.jpg //this should really be inside [Leep me Updated] array
[2] => value3.jpg //this should really be inside [Leep me Updated] array
}
from (this foreach creates puts in the values into $match)
foreach($data as $d)
{
if (isset($match[$d['data']['name']])) {
$match_loser = array($d['loser']['lrg_img']);
array_splice($match,1,0,$match_loser);
}else{
$match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
$d['loser']['lrg_img']);
}
}
What I'm trying to get is bring [0],[1],[2] into the [Keep me Updated] $match array:
Array
(
[Keep me Updated] => Array
(
[winner] => winnerl.jpg
[0] => value0.jpg
[1] => value1.jpg // old one: [0] => valuel.jpg
[2] => value2.jpg // old one: [1] => value2.jpg
[3] => value3.jpg // old one: [2] => value3.jpg
)
}
This is what $data looks like
$data[] = array(
"data"=>array
(
"name"=>$name,
),
"winner"=>array
(
"lrg_img"=>$img_url_winner
),
"loser"=>array
(
"lrg_img"=>$img_url_loser
)
$data has array values, and $match is where I'm trying to sort the data. So if my values match, it'll consolidate.
Thanks!
Use the inner array as the argument to array_splice
foreach($data as $d)
{
if (isset($match[$d['data']['name']])) {
$match_loser = array($d['loser']['lrg_img']);
array_splice($match[$d['data']['name']],1,0,$match_loser);
}else{
$match[$d['data']['name']] = array("winner"=>$d['winner']['lrg_img'],
$d['loser']['lrg_img']);
}
}