PHP array_search with associative array - php

I've an array's
first one:
[0] => 0289 [1] => 0146 [2] => 5519 [3] => 5308 [4] => 5503 [5] => 5357
second one(associative):
[78941] => 5308 [15749] => 5519 [1469156] => 5308 [78971413] => 5357 [418979] => 0289
Need to find keys in second one by first one value. One by one. I did some loop:
for($i=0;$i<=5;$i++){
$keys=array_search($first_array[$i],$second_array);
file_put_contents('check.txt',$keys,FILE_APPEND);
}
But get nothing. What I'am doing wrong?
Addition
The second array is more large than I show here, approximately 10000 values.
I must insert 5 values per file and these values must be uniq, to avoid overlap.
It will be looks like :
$t=0;
for($i=0;$i<=count($second_array);$i++){
$keys=array_search($first_array[$t],$second_array);
file_put_contents('check.txt',$keys,FILE_APPEND);
$t++
if ($t==5){$t=0}
}
Hope it would help.

If you need only keys, so just filter them:
$keys = array_intersect($first, array_keys($second));
However, if you want to get both values and keys, then it'll be like:
$keysAndValues = array_intersect_key($second, array_flip($first));

You can do it much simple way using foreach loop
<?php
$i = 0;
foreach($array2 as $key => $value):
if($array1[$i] == $value) {
//$key is the required key, manage your stuffs here.
}
$i++;
endforeach;
?>

foreach($first_array as $first_key => $first_value){
foreach($second_array as $second_key => $second_value){
if($first_value == $second_value){
file_put_contents($file_name, $second_key . "\n", FILE_APPEND);
}
}
}

array_search() returns the key if it finds the value, and returns false if not found, so if
you want keys, this code is what you want:
$one=array("0"=>"0146","1"=>"5519","2"=>"5308","3"=>"5503","4"=>"5357");
$two=array("78941"=>"5308","15749"=>"5519","1469156"=>"5308","78971413"=>"5357","418979"=>"5357");
$result=array();
for($i=0;$i<=5;$i++){
if(array_search($one[$i],$two))
$result[]=array_search($one[$i],$two);
}
print_r($result);//OR file_put_contents('check.txt',$result,FILE_APPEND)

Related

How to start a foreach from a specific key and continue after that to the rest of the array?

I have an array that contains key-value:
Array
(
[monday_deal] => 753394
[tuesday_deal] => 753401
[wednesday_deal] => 753435
[thursday_deal] => 753437
[friday_deal] => 771844
[saturday_deal] => 15047
[sunday_deal] => 753437
)
I need to start a foreach that starts from the today's day deal (key = wednesday_deal), for eg.
I need to know the deal ID of Wednesday first and then continue to get the deal IDs of Thurdsay, Friday, Saturday, Sunday, Monday, Tuesday serially.
NOTE: I wish to use foreach and not for since I have to make use of $key and $value combinations further in the code.
Use array_search on the keys to find the position of your key and then use array_slice to return the relevant part of the array. If you only need the deal ids, use array_values on the result, if you need more, use it in foreach.
<?php
$data = [
'monday_deal' => 753394,
'tuesday_deal' => 753401,
'wednesday_deal' => 753435,
'thursday_deal' => 753437,
'friday_deal' => 771844,
'saturday_deal' => 15047,
'sunday_deal' => 753437,
];
$pos = array_search('wednesday_deal', array_keys($data));
if ($pos===false) {
//error
}
$resultArray = array_slice($data, $pos);
//either
$resultDeals = array_values($resultArray);
$firstDeal = $resultDeals[0];
//or
foreach ($resultArray as $key=>$value) {
echo "$key => $value";
}
Of course if Wednesday deal is always at 3rd position, you can skip the array_search

php strangely nested key/value array - how to transform/map to be more usable? [duplicate]

This question already has answers here:
Generate an associative array from an array of rows using one column as keys and another column as values
(3 answers)
Closed 5 months ago.
The Microsoft QnAMaker API is returning a JSON key/value array (Metadata) in the following format:
$array = [[
"name" => "someName1",
"value" => "someValue1",
],
[
"name" => "someName2",
"value" => "someValue2",
],
..etc..
];
How do i transform it to be in the following more usable format:
$array = [
"someName1" => "someValue1",
"someName2" => "someValue2",
..etc..
];
I know I can do it using a loop... Is there a way to leverage on built in functions?
If a loop is the only way, how would you write it and why (performance/readibility/etc.)?
If it looks JSONish, array_column helps. Simply:
<?php
var_export(array_column($array, 'value', 'name'));
Output:
array (
'someName1' => 'someValue1',
'someName2' => 'someValue2',
)
This uses a combination of array_map() to re-map each element and then array_merge() to flatten the results...
print_r(array_merge(...array_map(function($data)
{ return [ $data['name'] => $data['value']]; }
, $array)));
It's not very elegant and would be interesting to see other ideas around this.
Which gives...
Array
(
[someName1] => someValue1
[someName2] => someValue2
)
There isn't really a way besides a loop, so just loop through the array, and create a new array the way you need it.
$new_array = [];
foreach($array as $row) {
$new_array[$row['name']] = $row['value'];
}
print_r($new_array);
There may be a few functions you can tie together to do what you want, but in general, the loop would probably be more readable and easier in overall.
As my previous answer was a dupe of GrumpyCroutons, I thought I'd rewrite with many array functions for good measure. (But don't use this, just do a simple foreach).
<?php
array_walk($array, function($v) use (&$result) {
$result[array_shift($v)] = array_values($v)[0];
});
var_export($result);
Output:
array (
'someName1' => 'someValue1',
'someName2' => 'someValue2',
)
This works:
$res = [];
array_walk($array, function(&$e) use(&$res) {
$res[$e['name']] = $e['value'];
unset($e); // this line adds side effects and it could be deleted
});
var_dump($res);
Output:
array(2) {
["someName1"]=> string(10) "someValue1"
["someName2"]=> string(10) "someValue2"
}
You can simply use array_reduce:
<?php
$output = array_reduce($array, function($a, $b) {
$a[$b['name']] = $b['value'];
return $a;
});
var_export($output);
Output:
array (
'someName1' => 'someValue1',
'someName2' => 'someValue2',
)
While getting a shift on (a non-foreach):
<?php
$c = $array;
while($d = array_shift($c))
$e[array_shift($d)] = array_shift($d);
var_export($e);
Output:
array (
'someName1' => 'someValue1',
'someName2' => 'someValue2',
)
Although it suggests in the comments in the manual that shifting is more expensive than popping. You could replace the initial assignment to $c above with an array_reverse and the while-shift with a while-pop.
However, either approach is probably lousy compared to a foreach, but here for who knows whos amusement.

Restructuring Multi Dimensional Array Format

I am struggling with what would appear to be a pretty straight forward task. I have looked at and tried all kinds of functions and suggestion on SO hoping that maybe there is something simple and functional out there. Nothing I tried gives me the logic to do the restructuring.
I have a long complex array. However very much simplified the logic problem I am trying to solve generically is as follows:
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name = Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
and I need to convert it to the following set of arrays (noting the concatenation of the two arrays with a common property id.....
$property1
(
array['charges']
[0] =>IPS2
array ['names']
[0] =>NAME-A
)
$property2
(
array['charges']
[0] ->IPS3
[1] =>IPS4
array['names']
[0] =>NAME-B
[1] =>NAME-c
)
I have tried everything over the course of the last few hours and a simple solution totally evades me.
If you can join the three arrays as you say in comments above this code will generate the look you want.
I loop through the array with property and keep key as the key to find names and charges in the other subarrays.
$cost_type = Array
(
0 => "ISP2",
1 => "ISP3",
2 => "ISP4"
);
$supplier_name =Array
(
0 => "NAME-A",
1 => "NAME-B",
2 => "NAME-C"
);
$propertyid = Array
(
0 => "property1",
1 => "property2",
2 => "property2"
);
$arr[] = $cost_type;
$arr[] = $supplier_name;
$arr[] = $propertyid;
$result = array();
Foreach($arr[2] as $key => $prop){
$result[$prop]["charges"][] =$arr[0][$key];
$result[$prop]["names"][] = $arr[1][$key];
}
Var_dump($result);
https://3v4l.org/EilvE
The following code converts the original array in the expected result:
$res = array();
foreach($arr[2] as $k => $foo){ // foreach property
if(!isset($res[$foo])){ // add property if not yet in list
$res[$foo] = array(
'charges' => array($arr[0][$k]),
'names' => array($arr[1][$k])
);
}else{ // add new value to already existing property
$res[$foo]['charges'][] = $arr[0][$k];
$res[$foo]['names'][] = $arr[1][$k];
}
}
Check it out here: https://eval.in/904473
Of course, it assumes a bunch on things about the data, but it should work for any number of items.
And if you need the property in another variable, just access it with $res['name of it].
Run this code you will get smiler result as you want :
$twodimantion=array();
$properties=array('property1','property2','property3');
$charges=array('ISP2','ISP3','ISP4');
$names=array('NAME-A','NAME-B','NAME-C');
foreach ($properties as $key => $property) {
$twodimantion['charge'][$key]=$charges[$key];
$twodimantion['names'][$key]=$names[$key];
$twoarray[$property]=$twodimantion;
}
echo '<pre>';
print_r($twoarray);
echo '</pre>';
I can't say I completely follow what you are trying to do, but I think this may be part of the way there for you.
When trying to restructure data in PHP, it's often helpful to create a empty array (or other data structure) to store the new data in first. Then you find a way to loop over your initial data structure that allows you to insert items into your reformatted structure in the right sequence.
<?php
$properties = []; // Array to hold final result
// Loop over your initial inputs
foreach ($groupsOfValues as $groupName => $groupValues) {
$temp = []; // Array to hold each groupings reformatted data
// Loop over the items in one of the inputs
for ($i=0; $i<count($group) && $i<count($properties)+1; $i++) {
if (!is_array($temp[$groupName])) {
$temp[$groupName] = [];
}
$temp[$groupName][] = $group[$i];
}
$properties[] = $temp;
}

Modify Current Value of Multidimensional Array

I have three arrays, say multiarray, valsarray, and otherarray. otherarray is a multidimensional array that supplies values to multiarray and valsarray, but besides that it is unimportant here. valsarray takes values from a subarray of each value in otherarray and multiarray takes straight values from otherarray, as demonstrated below:
foreach($otherarray as $other){
foreach($other as $sub){
$valsarray[] = $sub
}
$multiarray[] = array('Val1' => $other['Val1'], 'Val2' => $other['Val2']);
}
Now what I would like to do is append each key/value pair in valsarray to the current array entry of multiarray, to achieve a result similar to:
$multiarray = array('Val1' => $other['Val1'], 'Val2' => $other['Val2'],
'VALSARRAY_KEY1' => VALSARRAY_VALUE1, ..., 'VALSARRAY_KEYN' => VALSARRAY_VALUEN)
I have attempted to solve this using current in the following fashion:
foreach($valsarray as $key => $val){
current($multiarray)[$key] = $val;
}
But the multiarray remained unaltered. I may be misunderstanding how current works, or how to approach this problem, so any help or direction would be appreciated.
EDIT- EXAMPLE
otherarray = array(...prior array entries...,
array('Val1' => 'abc',
'Val2' => 'cde',
'Val3' => 'not important',
'Val4' => array(0 => 'subA', 1 => 'subB'),
...next array entries...);
BEFORE MERGE:
multiarray = array(...prior entries...,
array('Val1' => 'abc',
'Val2' => 'cde'));
valsarray = array(0 => 'subA', 1 => 'subB');
AFTER MERGE:
multiarray = array(...prior entries...,
array('Val1' => 'abc',
'Val2' => 'cde',
0 => 'subA',
1 => 'subB'));
So if multiarray was a regular array instead of a multidimensional one, I would do something like:
foreach($valsarray as $key => $val){
$multiarray[$key] = $val;
}
To achieve the end result.
I am not 100% sure what you are trying to accomplish a Minimal, Complete, and Verifiable example may help if I have misunderstood something.
It appears that the current() function does not work as you assume. (Or more specifically, the internal pointer.)
If you look at the example in the PHP documentation: Current(), you will see that for current($array) to change elements, you need to call next($array) or prev($array).
These function move the internal pointer of the array.
Note that in PHP 5, foreach loops use the internal pointer (and reset it when you start a loop), but in PHP 7, foreach loops do not use the internal pointer.
Anyway, here is my best guess at what could help you.
$valsarray_index = 0;
foreach ($otherarray as $other) {
$multiarray_value = array('Val1' => $other['Val1'], 'Val2' => $other['Val2']);
foreach ($other as $sub) {
$multiarray_value[$valsarray_index] = $sub;
// $multiarray_value["VALSARRAY_KEY" . $valsarray_index] = $sub;
$valsarray[] = $sub;
$valsarray_index += 1; // This stays in lockstep with the last index of $valsarray
}
$multiarray[] = $multiarray_value;
}
I am not exactly sure about what you want the final output to look like. If this produces incorrect information, then if would be helpful to provide some specific arrays for input and what you expect as output.

Multidimensional array loop php

New to programming so please explain as simply as possible. I have an array as $inputs. That array has rows as row0, row1 and on. Each row has key value pairs such as name='shay', age='23' and a few other things. I need to put those values in a database, but I can't figure out how to get to them and the examples I find go right over my head. I have made a loop with
for ($i = 0, $nums = count($inputs); $i < $nums; $i++)
But once inside of that loop I am lost as to what comes next. Please help.
The array looks as follows:
$inputs =array (
'row' => array (
0 => array ( 'id' => '2869', 'name' => 'shay', 'age' => '23',),
1 => array ( 'id' => '2868', 'name' => 'Tim', 'age' => '30',),
What I need to do is go through and do an insert with $name, $age etc. So I created the for loop, but I have no idea what to do inside of it to get the values of name and age etc for each row. I know how to insert them, it's just getting the values out of the array.
When I use
foreach ($inputs as $key => $row)
I can then do
dd($row['0']);
And return the contents of a row that I would then like to put in my query. I just don't really understand how to go from the dd() to actually accessing the values for each rows in a way that I could insert them.
You can loop over that data like this:
foreach($inputs as $key => $row) {
echo "row $key:\n";
foreach ($row as $person) {
echo " - " . $person['name'], " is ", $person['age'], " old.\n";
}
}
See it run on eval.in
Output based on the input you provided:
row row:
- shay is 23 old.
- Tim is 30 old.

Categories