I have three following arrays.
Array ( [0] => 395 [1] => 295 )
Array ( [0] => 5a3a13f237715637629.jpeg [1] => 5a3b602654cfd527057.jpg )
Array ( [0] => Seller Test Product [1] => Offline Product for Test )
The first array is the quantity, the second array is for the images, the third array is for the name of the products.
I want to combine all these three array into one and display it using foreach loop in PHP.
if I use array_merge(), I am getting the output:
Array ( [0] => 395 [1] => 295 ) Array ( [0] => 5a3a13f237715637629.jpeg [1] => 5a3b602654cfd527057.jpg ) Array ( [0] => Seller Test Product [1] => Offline Product for Test ) Array ( [0] => 5a3a13f237715637629.jpeg [1] => 5a3b602654cfd527057.jpg [2] => Seller Test Product [3] => Offline Product for Test [4] => 395 [5] => 295 )
Now, how can I display it using foreach loop in the view.
in the view the code is :
<?php foreach($c as $key => $strs)
{ ?>
<img style="width:150px;" src="<?php echo #getimagesize(base_url("assets/upload/product/".$key)) ? base_url("assets/upload/product/".$key):'http://placehold.it/350x200';?>" class="img-responsive">
<input type="text" name="vala" value="<?php echo $strs; ?>">
<input type="text" name="valas" value="<?php echo $strss; ?>">
<?php } ?>
Any help is welcome.
So what you really want is to group all fields of all arrays together. Values with the same index shall be merged into a single object. array_map() can be used for this.
$final = array_map(function($quantity, $image, $name) {
return (object)['quantity' => $quantity, 'image' => $image, 'name' => $name];
}, $quantityArray, $imageArray, $nameArray);
The result will be:
[
{
'qunatity' => 395,
'image' => '5a3a13f237715637629.jpeg',
'name' => 'Seller Test Product'
},
{
'qunatity' => 295,
'image' => '5a3b602654cfd527057.jpeg',
'name' => 'Offline Product for Test'
}
]
You can then address them in your foreach like this:
foreach($final as $product) {
echo $product->name;
echo $product->image;
echo $product->quantity;
}
For those of you who are in a real hurry, the following call to array_map() will do the same trick, but without mapping the array fields to a specific key in the new multidimensional array:
$final = array_map(NULL, $quantityArray, $imageArray, $nameArray);
The result will be:
[
[
0 => 395,
1 => '5a3a13f237715637629.jpeg',
2 => 'Seller Test Product'
],
[
0 => 295,
1 => '5a3b602654cfd527057.jpeg',
2 => 'Offline Product for Test'
],
]
The inner arrays of the newly created mltidimensinal array will be filled in the order of which the arrays were provided to array_map().
You can loop one array and use key to get the corresponding value from the other arrays.
$a=array ( 0 => 395,1 => 295 );
$b=array ( 0 =>" 5a3a13f237715637629.jpeg" ,1 => "5a3b602654cfd527057.jpg" ) ;
$c=array ( 0 => "Seller Test Product",1 => "Offline Product for Test" );
Foreach($a as $key => $val){
$res[$key]['qty'] = $val;
$res[$key]['img'] = $b[$key];
$res[$key]['desc'] = $c[$key];
}
Var_dump($res);
Output:
array(2) {
[0]=>
array(3) {
["qty"]=> int(395)
["img"]=> string(25) " 5a3a13f237715637629.jpeg"
["desc"]=> string(19) "Seller Test Product"
}
[1]=>
array(3) {
["qty"]=> int(295)
["img"]=> string(23) "5a3b602654cfd527057.jpg"
["desc"]=> string(24) "Offline Product for Test"
}
}
https://3v4l.org/h8B0u
Example Code
<?php
$array1=array ( 0 => 395,1 => 295 );
$array2=array ( 0 =>" 5a3a13f237715637629.jpeg" ,1 => "5a3b602654cfd527057.jpg" ) ;
$array3=array ( 0 => "Seller Test Product",1 => "Offline Product for Test" );
echo "<pre>";
print_r($array1);print_r($array2);print_r($array3);
$result=array_merge($array1,$array2,$array3);
print_r($result);
?>
Related
I have the following array
Array
(
[tags] => Array
(
[0] => hello
)
[assignee] => 60b6a8a38cf91900695dd46b
[multiple_assignee] => Array
(
[0] => Array
(
[accountId] => 60b6a8a38cf91900695dd46b
)
[1] => Array
(
[accountId] => 5b39d23d32e26a2de15f174f
)
)
)
I want to remove 60b6a8a38cf91900695dd46b from the multiple_assignee array.
I have tried with the following code:
if (($key = array_search($this->getUsersHashMapValue($responsiblePartyIds[0]), $mutipleAssignee)) !== false) {
unset($mutipleAssignee[$key]['accountId']);
}
But it is not removing that element. The intention is I don't want to repeat the 60b6a8a38cf91900695dd46b assignee in the multiple assignee array.
I have also tried with the following code:
foreach($mutipleAssignee as $subKey => $subArray){
if($subArray['accountId'] == $this->getUsersHashMapValue($responsiblePartyIds[0])){
unset($mutipleAssignee[$subKey]);
}
}
But it is resulting as
Array
(
[tags] => Array
(
[0] => hello
)
[assignee] => 60b6a8a38cf91900695dd46b
[multiple_assignee] => Array
(
[1] => Array
(
[accountId] => 5b39d23d32e26a2de15f174f
)
)
)
rather than
[multiple_assignee] => Array
(
[0] => Array
(
[accountId] => 5b39d23d32e26a2de15f174f
)
)
Thank you
Just extract the accountId column and search that. Then use that key:
$key = array_search($this->getUsersHashMapValue($responsiblePartyIds[0]),
array_column($mutipleAssignee, 'accountId'));
unset($mutipleAssignee[$key]);
After your edit it seems you just want to reindex the subarray after unset:
$mutipleAssignee = array_values($mutipleAssignee);
I would just use a simple for loop. All of the array_* functions are really helpful but I find that they hide nuances. Since I don't have your functions I'm just making a plain-old one, but you should be able to port this.
$data = [
'tags' => [
'hello',
],
'assignee' => '60b6a8a38cf91900695dd46b',
'multiple_assignee' => [
[
'accountId' => '60b6a8a38cf91900695dd46b',
],
[
'accountId' => '5b39d23d32e26a2de15f174f',
],
],
];
$assignee = $data['assignee'];
foreach ($data['multiple_assignee'] as $multiple_assignee_key => $multiple_assignee) {
// if the root assignee is also listed in the multiple assignee area
if ($multiple_assignee['accountId'] === $assignee) {
// remove the duplicate from the multiple area
unset($data['multiple_assignee'][$multiple_assignee_key]);
// re-index the array
$data['multiple_assignee'] = array_values($data['multiple_assignee']);
}
}
This outputs:
array(3) {
["tags"]=>
array(1) {
[0]=>
string(5) "hello"
}
["assignee"]=>
string(24) "60b6a8a38cf91900695dd46b"
["multiple_assignee"]=>
array(1) {
[0]=>
array(1) {
["accountId"]=>
string(24) "5b39d23d32e26a2de15f174f"
}
}
}
Demo here: https://3v4l.org/tYppK
I try to import an XML file:
<works_list>
<licenses>
<name>First Company Name</name>
<work_address_list>
<address_place>
<address>36234020,first address </address>
<works>
<work>Service 1</work>
<work>Service 2</work>
<work>Service 3</work>
</works>
</address_place>
<address_place>
<address>36234020,second address</address>
<works>
<work>Service 1</work>
<work>Service 3</work>
</works>
</address_place>
</work_address_list>
</licenses>
<licenses>
...
</licenses>
</works_list>
and I want to put it in array:
$companyName = [
[
'address' => '36234020,first address',
'works' => ['Service 1', 'Service2', 'Service3']
],
[
'address' => '36234020,second address',
'works' => ['Service 1', 'Service3']
]
]
With this code
$node = simplexml_import_dom($doc->importNode($reader->expand(), true));
$companyName = (string) $node->name;
foreach ($node->work_address_list as $item) {
var_dump($item);
}
I get all elements in var_dump:
object(SimpleXMLElement)#29 (1) { ["address_place"]=> array(2) { [0]=> object(SimpleXMLElement)#30 (7) { ["address"]=> string(142) "36234020,first address" ["works"]=> object(SimpleXMLElement)#32 (1) { ["work"]=> array(3) { [0]=> string(121) "Service 1" [1]=> string(117) "Service 2" [2]=> string(117) "Service 3" } } } [1]=> object(SimpleXMLElement)#31 (7) { ["address"]=>'..'..}
How can I access all elements and put it in array?
I thought that $company_places[] = $item->address_place; will create two arrays but it doesn't work.
You can use simplexml_load_file if you're trying to read from an XML file. Then use json_encode and json_decode respectively.
<?php
$xml = simplexml_load_file('filename.xml');
$json = json_encode($xml);
$array = json_decode($json, true);
print_r($array);
Output:
Array
(
[licenses] => Array
(
[name] => First Company Name
[work_address_list] => Array
(
[address_place] => Array
(
[0] => Array
(
[address] => 36234020,first address
[works] => Array
(
[work] => Array
(
[0] => Service 1
[1] => Service 2
[2] => Service 3
)
)
)
[1] => Array
(
[address] => 36234020,second address
[works] => Array
(
[work] => Array
(
[0] => Service 1
[1] => Service 3
)
)
)
)
)
)
)
I have 2 array's, first array have for example ItemID of my item, second array have description about my item. I want to match data into 1 array.
It looks like:
[rgInventory] => Array
(
[1234567890] => Array
(
[id] => 1234567890
[classid] => 123456789
[instanceid] => 987654321
[amount] => 1
[pos] => 1
)
)
[rgDescriptions] => Array
(
[192837465_918273645] => Array
(
[appid] => 730
[name] => Something
)
)
Items in arrays don't have the same value like ID, but they are in the same order so:
Description for the first item in rgInventory is in the first array inside rgDescriptions.
What should I do to match for example id from rgInventory with name from rgDescriptions in the same array for example $backpack = array();?
Regards for you.
Try this:
<?php
$array1 = array('rgInventory' =>
array(
'1234567890' => array(
'id' => 1234567890,
'classid' => 123456789,
'instanceid' => 987654321,
'amount' => 1,
'pos' => 1
)
)
);
$array2 = array(
'rgDescriptions' => array(
'192837465_918273645' => array(
'appid' => 730, 'name' => 'Something')
)
);
Create new function to combine the two arrays into one array:
function array_sum_recursive($data1, $data2) {
if (!is_array($data1) && !is_array($data2)) {
return $data1 + $data2;
}
// deepest array gets precedence
if (!is_array($data2)) {
return $data1;
}
if (!is_array($data1)) {
return $data2;
}
//merge and remove duplicates
$keys = array_unique(array_merge(array_keys($data1), array_keys($data2)));
foreach ($keys as $key) {
if (isset($data1[$key]) && isset($data2[$key])) {
$result[$key] = array_sum_recursive($data1[$key], $data2[$key]);
} else if (isset($data1[$key])) {
$result[$key] = $data1[$key];
} else {
$result[$key] = $data2[$key];
}
}
if(empty($result)){
echo "no result";
die();
}else{
return $result;
}
}
Put the two array in one array $newarray:
$newonearray = array_sum_recursive($array1, $array2);
echo '<pre>';
print_r($newonearray);
?>
And you will get this:
Array
(
[rgInventory] => Array
(
[1234567890] => Array
(
[id] => 1234567890
[classid] => 123456789
[instanceid] => 987654321
[amount] => 1
[pos] => 1
)
)
[rgDescriptions] => Array
(
[192837465_918273645] => Array
(
[appid] => 730
[name] => Something
)
)
)
Hope this may help.
You can use function each to get each element of both arrays, then merge its with array_merge and save this new item to backup array.
Try something like this
<?php
$rgInventory = ['firstInv' => ['invId' => 1], 'secondInv' => ['invId' => 2]];
$rgDescriptions = ['firstDesc' => ['descId' => 1], 'secondDesc' => ['descId' => 2]];
if (count($rgInventory) && count($rgInventory) == count($rgDescriptions)) {
$backpack = [];
while($inventory = each($rgInventory)) {
$description = each($rgDescriptions);
$item = array_merge($inventory['value'], $description['value']);
$backpack[] = $item;
}
var_dump($backpack);
}
Output will be:
array(2) {
[0]=>
array(2) {
["invId"]=>
int(1)
["descId"]=>
int(1)
}
[1]=>
array(2) {
["invId"]=>
int(2)
["descId"]=>
int(2)
}
}
I am making a session based shopping cart system, and I need some help with displaying the array from the session. My array looks like this:
array(5) { [0]=> NULL [1]=> string(5) "TMRS1" [2]=> string(5) "TMRS2" [3]=> string(5) "TMRS1" [4]=> string(5) "TMRS3" }
I would like a script to count duplicate elements and display them.
For instance, TMRS1 would be set to $name1 (= TMRS1) and $quantity1 (= 2). The next item would then be $name2 and $quantity2 and so on.
Is this possible? You are more than welcome to post if you've got a better idea on how I can display the items in the cart. I just have to be able to pull some data from a database by using the name of the items, and then add up all the prices of the items :)
maybe you can use array_count_values()
example from php.net
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
The above example will output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
With the array you give:
$shopping_cart = array("TMRS1","TMRS2","TMRS1","TMRS3");
$items_count = array_count_values($shopping_cart);
echo "Number of TMRS1 in the cart:".$item_count["TMRS1"];
This would leave you with an array with the data you need:
<?php
$tmrs = array(NULL, "TMRS1", "TMRS2", "TMRS1", "TMRS3");
foreach ($tmrs as $key => $val){
$duplicateArray[$key]['name'] = "TMRS" . $key; // only the name
$duplicateArray[$key]['quantity'] = (int) str_replace("TMRS", "", $val); // aquire only the value
}
print_r($duplicateArray);
?>
That would return:
Array
(
[0] => Array
(
[name] => TMRS0
[quantity] => 0
)
[1] => Array
(
[name] => TMRS1
[quantity] => 1
)
[2] => Array
(
[name] => TMRS2
[quantity] => 2
)
[3] => Array
(
[name] => TMRS3
[quantity] => 1
)
[4] => Array
(
[name] => TMRS4
[quantity] => 3
)
)
You could then output the name or the value like this:
<?php echo $duplicateArray[2]['name']; ?>
This is my array :
Array
(
[0] => Array
(
[0] => S No.
[1] => Contact Message
[2] => Name
[3] => Contact Number
[4] => Email ID
)
[1] => Array
(
[0] => 1
[1] => I am interested in your property. Please get in touch with me.
[2] => lopa <br/>(Individual)
[3] => 1234567890
[4] => loperea.ray#Gmail.com
)
[2] => Array
(
[0] => 2
[1] => This user is looking for 3 BHK Multistorey Apartment for Sale in Sohna, Gurgaon and has viewed your contact details.
[2] => shiva <br/>(Individual)
[3] => 2135467890
[4] => sauron82#yahoo.co.in
)
)
How can I retrieve all data element wise?
You can get information about arrays in PHP on the official PHP doc page
You can access arrays using square braces surrounding the key you like to select [key].
So $array[1] will give yoo:
Array
(
[0] => 1
[1] => I am interested in your property. Please get in touch with me.
[2] => lopa <br/>(Individual)
[3] => 1234567890
[4] => loperea.ray#Gmail.com
)
And $array[1][2] will give you:
lopa <br/>(Individual)
Or you can walkt through the elements of an array using loops like the foreach or the for loop.
// perfect for assoc arrays
foreach($array as $key => $element) {
var_dump($key, $element);
}
// alternative for arrays with seamless numeric keys
$elementsCount = count($array);
for($i = 0; $i < $elementsCount; ++$i) {
var_dump($array[$i]);
}
You have integer indexed elements in multidimensional array. To access single element from array, use array name and it's index $myArray[1]. To get inner element of that previous selected array, use second set of [index] - $myArray[1][5] and so on.
To dynamically get all elements from array, use nested foreach loop:
foreach ($myArray as $key => $values) {
foreach ($values as $innerKey => $value) {
echo $value;
// OR
echo $myArray[$key][$innerKey];
}
}
The solution is to use array_reduce:
$header = array_map(
function() { return []; },
array_flip( array_shift( $array ) )
); // headers
array_reduce( $array , function ($carry, $item) {
$i = 0;
foreach( $carry as $k => $v ) {
$carry[$k][] = $item[$i++];
}
return $carry;
}, $header );
First of all we get the header from the very first element of input array. Then we map-reduce the input.
That gives:
$array = [['A', 'B', 'C'], ['a1', 'b1', 'c1'], ['a2', 'b2', 'c2'], ['a3', 'b3', 'c3']];
/*
array(3) {
'A' =>
array(3) {
[0] =>
string(2) "a1"
[1] =>
string(2) "a2"
[2] =>
string(2) "a3"
}
'B' =>
array(3) {
[0] =>
string(2) "b1"
[1] =>
string(2) "b2"
[2] =>
string(2) "b3"
}
'C' =>
array(3) {
[0] =>
string(2) "c1"
[1] =>
string(2) "c2"
[2] =>
string(2) "c3"
}
}
*/
I think this is what you are looking for
$array = Array
(
0=> Array
(
0 => 'S No.',
1 => 'Contact Message',
2 => 'Name',
3 => 'Contact Number',
4 => 'Email ID'
),
1 => Array
(
0 => 1,
1 => 'I am interested in your property. Please get in touch with me.',
2 => 'lopa <br/>(Individual)',
3 => '1234567890',
4 => 'loperea.ray#Gmail.com',
),
2 => Array
(
0 => 2,
1 => 'This user is looking for 3 BHK Multistorey Apartment for Sale in Sohna, Gurgaon and has viewed your contact details.',
2 => 'shiva <br/>(Individual)',
3 => '2135467890',
4 => 'sauron82#yahoo.co.in',
)
);
$result_array = array();
array_shift($array);
reset($array);
foreach($array as $x=>$array2){
foreach($array2 as $i => $arr){
if($i == 1){
$result_array[$x]['Contact Message'] = $arr;
}elseif($i == 2){
$result_array[$x]['Name'] = $arr;
}elseif($i == 3){
$result_array[$x]['Contact Number'] =$arr;
}elseif($i == 4){
$result_array[$x]['Email ID'] = $arr;
}
}
}
print_r($result_array);