Formating a single result in php multidimensional to match? - php

I'm grabbing a some XML data and parsing it with PHP.
Most of the results come in multidimensional array but occasionally I'll get a result in a single array and it breaks my script.
I'm trying to format the single result to match the format of the results in the multidiminsonal array but I'm not having any luck.
Here is what I got:
Array
(
[name] => Steve Jobs
[id] => 3
)
Array
(
[0] => Array
(
[name] => Steve Jobs
[id] => 6
)
[1] => Array
(
[name] => Bill Gates
[id] => 8
)
)
I'm trying to format the single result to match the multidimensional format then flatten...
Array
(
[0] => Array
(
[name] => Steve Jobs
[id] => 3
)
[1] => Array
(
[name] => Steve Jobs
[id] => 6
)
[2] => Array
(
[name] => Bill Gates
[id] => 8
)
)
I've tried this:
$array_check = #array_keys($result[0]['name']);
if ($array_check[0] == "0") {
$result;
} elseif ($array_check[0] == "name") {
$ReWrite = array ([0] =>
array (['name']=>
array ($result[0]['name'])
));
$result = $ReWrite;
}
I thought that would do it but it's off...

Try this:
$array_check = #array_keys($result[0]['name']);
if (!isset($array_check[0])) {
$result[] = $array_check;
} else {
$result = $array_check;
}
var_dump($result);

If your first array was assigned to the variable $singleArray and your target results stored in $results, try this array_push($results, $singleArray);
Use this together with reset() it returns the first element of an array:
if(!is_array(reset($result))){
array_push($results, $result);
}
This will test if the array does not contain an array as an element, if it doesn't push the whole array to an aggregate array.
Edit: Try this loop:
for($i = 0; $i <= count($multi); $i++){
$arr = $multi[$i];
if(!is_array($arr)){
$multi[$i] = array($arr);
}
} var_dump($multi);

Related

How to count the leaf elements of assocaitive/nested array

I have been trying to count the last leaf node elements in a array.
Im thinking along the lines of:
Getting a simple array of leaf elements from the testArray using: 'array_walk_recursive'.
Count elements in the new array using: 'array_count_values'.
Im unsure how to get a simple list array from 'array_walk_recursive', i just get a long string of values....or is there a better way of achieving this result?
DESIRED RESULT:
flammable = 1
irritant = 2
toxic = 3
PHP:
$testArray = Array
(
[0] => Array
(
[0] => toxic
[1] => irritant
[3] => flammable
)
[1] => Array
(
[0] => toxic
[1] => irritant
)
[2] => Array
(
[0] => toxic
)
);
array_walk_recursive($testArray, function(&$value)
{
echo 'string = '.$value;
print_r(newArray); //How can i get this new array list?
});
$counts = array_count_values($newArray); //and use this to count values?
Try this, the numbers should show up in the $groups array.
$groups = array();
array_walk_recursive($testArray, function(&$value) use (&$groups)
{
if (isset($groups[$value])) {
$groups[$value]++;
} else {
$groups[$value] = 1;
}
});
print_r($groups);

Put multiple arrays in one large associative array

I am creating a set of arrays with the following loop:
$assessmentArr = explode("&", $assessmentData);
foreach($assessmentArr as $data) {
$fullArr = explode("_", $data);
// Break down to only archetype and value
$resultArr = explode("=", $fullArr[2]);
//print_r($resultArr);
}
Which produces the following results:
Array
(
[0] => community-support
[1] => 24
)
Array
(
[0] => money-rewards
[1] => 30
)
Array
(
[0] => status-stability
[1] => 15
)
Array
(
[0] => personal-professional-development
[1] => 32
)
Array
(
[0] => community-support
[1] => 9
)
Array
(
[0] => money-rewards
[1] => 12
)
Array
(
[0] => status-stability
[1] => 16
)
Array
(
[0] => personal-professional-development
[1] => 29
)
I need to combine these into one array, and where the [0] value matches, I need to add the [1] value together.
So I would like the final output to be something like:
Array
(
[community-support] => 33
[money-rewards] => 42
[status-stability] => 31
[personal-professional-development] => 61
)
I found this question: How to merge two arrays by summing the merged values which will assist me in merging and adding the values together, but I'm not sure how to go about it when the arrays aren't assigned to a variable. Is what I am trying to do possible or am I going about this the wrong way?
Don't make it complicated, just check if the results array already has an element with that key and if not initialize it otherwise add it. E.g.
(Add this code in your loop):
if(!isset($result[$resultArr[0]]))
$result[$resultArr[0]] = $resultArr[1];
else
$result[$resultArr[0]] += $resultArr[1];
Then you have your desired array:
print_r($result);
You could do it like this
$assessmentArr = explode("&", $assessmentData);
$finalArr = array();
foreach($assessmentArr as $data) {
$fullArr = explode("_", $data);
// Break down to only archetype and value
$resultArr = explode("=", $fullArr[2]);
if(array_key_exists($resultArr[1], $finalArr)){
$finalArr[$resultArr[0]] += $resultArr[1];
}else{
$finalArr[$resultArr[0]] = $resultArr[1];
}
}
First check, if the key already exists in the array, if so you add the value to the value in the final array. Otherwise you add the new index to the final array, with the value from resultArr as inital value.
... way too slow :/

PHP Split array in subarrays

Note, array_chunk is not my solution (It seems to me).
I have an array of about 150.000 elements
Array
(
[0] => Array
(
[name] => Danilo
[phone] => 33568
)
[1] => Array
(
[name] => Alessandro
[phone] => 392222
)
[2] => Array
(
[name] => Alex
[phone] => 3922
)
[3] => Array
(
[name] => Capa
[phone] => 392
)
)
And so on. I would split this array in several arrays, of (for example) 3.000 elements every one.
I saw array_chunk, but it returns a single array with several subarray.
I need several subarray to store them in a database and elaborate in future.
I'm getting crazy to write a snippet starting from that $temp and divide it into smaller array.
$size_chunks = 1;
$temp = array_chunk($recipients, $size_chunks);
foreach ($temp as $key=>$value)
{
if ($key<$size_chunks)
{
$to_store[] = $temp[$key];
}
//print_r($to_store);
// pseudo sql
// INSERT INTO table (sub_recipient) VALUES ($to_store);
$to_store = array();
}
So, every time that for loop end, reduce temp, store $to_store array and restart for others chunks.
Thank you very much.
PS in my example chunk==1 because starting array is small... ;)
With my example of chunk = 1, I need from starting array this 4 arrays:
Array
(
[0] => Array
(
[name] => Danilo
[phone] => 33568
)
)
Array
(
[0] => Array
(
[name] => Alessandro
[phone] => 39222
)
)
Array
(
[0] => Array
(
[name] => Alex
[phone] => 39222
)
)
Array
(
[0] => Array
(
[name] => Capa
[phone] => 392
)
)
Another explain
1 - With a starting array of 15.000 elements, and chunk of 3.000, I need in output (15.000 / 3.000) = 5 arrays. I will save them in database, so in DB I will have 5 rows (a row for every array).
2 - With a starting array of 4 elements, and chunk of 1, I need in output (4 / 1) = 4 arrays. I will save them in database, so in DB I will have 4 rows (a row for every array).
array_chunks() already does what you want, you just have to save it:
$chunks = array_chunk($array, $size_chunks);
foreach ($chunks as $chunk) {
// save $chunk to your database
}
$recipients = Array(
Array("fdbvfdb","dsacsdcds"),
Array("hrloo","dacdsc"),
Array("dcsdc","adcsd"),
Array("dcsdc","adcsd")
);
$total = count($recipients);//count 150.000 elements
$i=1;
for($i=0;$i<$total;$i++){
$O = array_slice($recipients,$i,1);
print_r($O);
//Your insert/Save code
}
you can use this code there is uses Array_Slice

Passing multiple arrays to a Cartesian function

I need to pass multiple array's in an indexed format to a cartesain function in order to calculate every permutation. This works when the code is:
$count = cartesian(
Array("GH20"),
Array(1,3),
Array(6,7,8),
Array(9,10)
);
I will not always know the length, number of arrays, or values so they are stored in another array "$total" which may look something like this:
Array (
[0] => Array
(
[0] => 1
[1] => 3
)
[1] => Array
(
[0] => 6
[1] => 7
[2] => 8
)
[2] => Array
(
[0] => 9
[1] => 10
)
)
I have tried implementing the user_call_back_function as per:
$count = call_user_func('cartesian', array($total));
However the array that then gets passed looks like this:
Array (
[0] => Array (
[0] => Array (
[0] => Array (
[0] => 1
[1] => 3
[2] => 4
)
[1] => Array (
[0] => 5
[1] => 6
[2] => 7
[3] => 8
)
[2] => Array (
[0] => 9
[1] => 10
)
)
)
)
Where am I going wrong, why is the array being buried further down in dimensions where it is not needed, and is this the reason why my cartesain function does no longer work?
Thanks, Nick
As requested, here is my cartesain function:
function cartesian() {
$_ = func_get_args();
if(count($_) == 0)
return array(array());
$a = array_shift($_);
$c = call_user_func_array(__FUNCTION__, $_);
$r = array();
foreach($a as $v)
foreach($c as $p)
$r[] = array_merge(array($v), $p);
return $r;
}
why is the array being buried further down in dimensions where it is not needed?
Simply because you are wrapping an array in another array when calling call_user_func.
$count = call_user_func('cartesian', array($total));
Perhaps you meant this:
$count = call_user_func('cartesian', $total);
is this the reason why my cartesain function does no longer work?
I don't know, you have not posted your cartesain, just an arrat called cartesain
EDIT as op updated the question.
If you are using PHP 5.6 you should be able to use the splat operator.
call_user_func("cartesain", ...$total);
Disclaimer, I have not tested this.
Arrays and Traversable objects can be unpacked into argument lists when calling functions by using the ... operator.

How to set new index in previous array using for each loop

here is my code
array 1:
Array
(
[0] => Array
(
[id] => 42166
[Company_Website] => http://www.amphenol-highspeed.com/
[company_name] => Amphenol High Speed Interconnect
[city_name] => New York
[country_name] => USA
[comp_img] =>
)
)
array 2:
Array
(
[0] => Array
(
[Product_Name] => CX to CX,Amphenol High Speed Active,Serial Attached SCSI
[company_id] => 42166
)
)
php code:
$total = count($result);
$i=0;
foreach ($result as $key=>$value) {
$i++;
$company_id= implode(",",(array)$value['id']);
if ($i != $total)
echo',';
}
code to fetch array 2:
foreach ($res as $key1=>$value1) {
echo $total;
$event[$value['company_name']] = $value1['Product_Name'];
if($value1['company_id']==$company_id )
{
echo " match";
//$key[['company_name']]= $value1['Product_Name'];
}
else
{
echo "not matched";
}
}
what i need create a new index if company_id is match with id of another array.
that is product_name.
if product name is there just create index otherwise show null.
i want show in key=> value .
output should be like:
Array
(
[0] => Array
(
[id] => 42166
[Company_Website] => http://www.amphenol-highspeed.com/
[company_name] => Amphenol High Speed Interconnect
[city_name] => New York
[country_name] => USA
[comp_img] =>
[Product_Name] => CX to CX,Amphenol High Speed Active,Serial Attached SCSI
)
)
Your all problems with keys in arrays will disappear when you will start using company ids as a keys.
To reindex you arrays, you can use:
$array1 = array_combine(array_column($array1, 'id'), $array1);
$array2 = array_combine(array_column($array2, 'company_id'), $array2);
In the output you will get:
array 1:
Array
(
[42166] => Array
(
[id] => 42166
...
)
)
And array 2 will looks similiar - id as a key.
So accessing to the elements using ids as a keys is a piece of cake right now.

Categories