php multidimensional array to single dimensional array [duplicate] - php

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 6 months ago.
I have an array
array(5) {
[0]=>
array(1) {
["id"]=>
string(1) "5"
}
[1]=>
array(1) {
["id"]=>
string(1) "6"
}
[2]=>
array(1) {
["id"]=>
string(1) "7"
}
[3]=>
array(1) {
["id"]=>
string(1) "8"
}
[4]=>
array(1) {
["id"]=>
string(1) "9"
}
}
I wan to make my array like:
$registrationIDs = array( "5","6","7","8","9");
I am trying this code but not working
$results = array();
foreach($result as $inner) {
$results[key($inner)] = current($inner);
}
How do I effeciently transform arrays like this

Try with array_map.
$results = array_map (function ($e) { return $e['id']; }, $inner);
http://php.net/manual/en/function.array-map.php
By the way, if you still want to do it your way, try this form of foreach :
$results = array ();
foreach ($inner as $key => $value)
$results[$key] = $value['id'];

$array = [['id'=>1],['id'=>2],['id'=>3],['id'=>4],['id'=>5],];
$result = call_user_func_array('array_merge_recursive', $array);
var_dump($result['id']);
//array(5) {
// [0] =>
// int(1)
// [1] =>
// int(2)
// [2] =>
// int(3)
// [3] =>
// int(4)
// [4] =>
// int(5)
//}

Ok, I saw a lot of answers, so I wondered what to better answer was.
<?php
$data = array ();
for ($i = 0; $i < 1000000; $i++)
$data[$i] = array ('id' => rand ());
$time0 = microtime (true);
// Niols (1)
$results = array_map (function ($e) { return $e['id']; }, $data);
$time1 = microtime (true);
// Niols (2)
$results = array ();
foreach ($data as $key => $value)
$results[$key] = $value['id'];
$time2 = microtime (true);
// User (1)
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
$results = iterator_to_array($it, false);
$time3 = microtime (true);
// User (2)
$results = array();
foreach ($data as $datum)
$results = array_merge($results, $datum);
$time4 = microtime (true);
// sectus
$results = call_user_func_array('array_merge_recursive', $data);
$time5 = microtime (true);
// Pankaj katiyar and Ghost
$results = array_column($data, 'id');
$time6 = microtime (true);
var_dump ($time1-$time0);
var_dump ($time2-$time1);
var_dump ($time3-$time2);
var_dump ($time4-$time3);
var_dump ($time5-$time4);
var_dump ($time6-$time5);
On my computer, this outputs :
float(0.62708687782288)
float(0.35285401344299)
float(1.5429890155792)
float(0.7408618927002)
float(0.70525908470154)
float(0.15015292167664)
Conclusion :
array_column is ultra-efficient (but PHP 5.5+). Writing a simple foreach seems quite efficient too.

You can try with below code.
I think this is working fine.
Process 1:-
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));
$l = iterator_to_array($it, false);
var_dump($l); // one Dimensional
Process 2:-
Try with:
$input = array(/* your array*/);
$output = array();
foreach ( $input as $data ) {
$output = array_merge($output, $data);
}

Try this:
$array = array(/*your array*/);
$results = array();
foreach ($array as $value)
{
foreach($value as $innerValue)
{
$results[] = $innervalue;
}
}

Related

Re-arranging and combining an array

I'm having an issue when I dump the array below. This dumps several arrays. Some are 2 some are 3, which complicates it even more. Basically what I want I put below. I have tried array_push, array_combine, array_merge, several different ways including $array[$param] = $insertValue and I'm stuck. I am open to creating a brand new array too.
Please note not all arrays are counts of 3 but always return at least 1.
Original array:
array(3) {
[0]=>
array(2) {
["contact_id"]=>
string(9) "CONTACTID"
["contact_id_content"]=>
string(19) "123456789123456"
}
[1]=>
array(2) {
["sm_owner"]=>
string(9) "SMOWNERID"
["sm_owner_content"]=>
string(19) "123456798452"
}
[2]=>
array(2) {
["contact_owner"]=>
string(13) "Contact Owner"
["contact_owner_content"]=>
string(16) "Jane Doe"
}
Array desired:
array(3) {
[0]=>
array(6) {
["contact_id"]=>
string(9) "CONTACTID"
["contact_id_content"]=>
string(19) "123456789123456"
["sm_owner"]=>
string(9) "SMOWNERID"
["sm_owner_content"]=>
string(19) "123456798452"
["contact_owner"]=>
string(13) "Contact Owner"
["contact_owner_content"]=>
string(16) "Jane Doe"
}
try this code:
$NewArray = array();
foreach($OriginalArray as $value) {
$NewArray[] = array_merge($value,$NewArray);
}
or you can use array_merge_recursive
let $result = [];
foreach ($yourarray as $key => $value) {
$result = $value;
}
var_dump($result);
Here you go: How to Flatten a Multidimensional Array? – Barmar 23 mins ago
function flatten($array)
{
return array_reduce($array, function($acc, $item){
return array_merge($acc, is_array($item) ? flatten($item) : [$item]);
}, []);
}
// loop the individual fields
for ($i=0; $i<count($row_data); $i++) {
$newArray = flatten([$i => $response_row]);
}
Try something like this:
function flatten(array $array) : array
{
$newArray = [];
foreach ($array as $subArray) {
foreach ($subArray as $key => $value) {
$newArray[$key] = $value;
}
}
return $newArray;
}

PHP Str_replace is not working in foreach loop

Here is my code.
I am trying to get inspect link for steam item. I have tried to use preg_replace but no luck either.
$API_link = sprintf("http://steamcommunity.com/id/*steamid*/inventory/json/730/2?trading=1");
$json = file_get_contents($API_link);
$json_output = json_decode($json);
$result = $json_output;
$link = array();
$id = array();
foreach($result->rgDescriptions AS $item){
$empty = array();
$newstring = $item->actions[0]->link;
if($newstring == NULL){
continue;
} else {
$empty['link'] = $newstring;
array_push($link, $empty);
}
}
foreach($result->rgInventory AS $inventory){
$empty = array();
if($inventory->instanceid == 0){
continue;
} else {
$empty['id'] = $inventory->id;
array_push($id, $empty);
}
}
$array = array_merge($id, $link);
foreach($array AS $final){
$assetid = "%assetid%";
echo str_replace($assetid, $final['id'], $final['link']);
}
}
But its not working. Please see if you can help.
As I can see you have array of arrays:
// bracket squares equivalent of array() keyword PHP >=v5.4
// here is
// $link = array(['link'=>'url'],['link'=>'url'])
// $id = array(['id'=>'id'],['id'=>'id'])
// result will be:
// array(['link']=>'url'],['link'=>'url'],['id'=>'id'],['id'=>'id'])
$array = array_merge($id, $link);
foreach($array AS $final){
// here is the first $final
// array('link'=>'url')
$assetid = "%assetid%";
// but here is we try to get
// 'id' and 'link'
echo str_replace($assetid, $final['id'], $final['link']);
}
I think it's some kind of mistake.
Ok, some test script:
<?php
$a = array( array('link'=>'hello1'), array('link'=>'hello2'));
$b = array( array('id'=>'id0'), array('id'=>'id1'));
$c = array_merge($a, $b);
var_dump($c);
result:
array(4) {
[0] =>
array(1) {
'link' =>
string(6) "hello1"
}
[1] =>
array(1) {
'link' =>
string(6) "hello2"
}
[2] =>
array(1) {
'id' =>
string(3) "id0"
}
[3] =>
array(1) {
'id' =>
string(3) "id1"
}
}
array_merge doesn't mix your associative arrays between them nether all nor particular item (I hope I explain it correct)
of course
foreach ($c as $item) {
var_dump($item);
}
will enumerate all the items one by one
array(1) {
'link' =>
string(6) "hello1"
}
array(1) {
'link' =>
string(6) "hello2"
}
array(1) {
'id' =>
string(3) "id0"
}
array(1) {
'id' =>
string(3) "id1"
}
and there is no array that has both of them (link and id) in the item
This script can't associate link and id properly, cause some of links can be skipped by continue, some of id also can be skipped. And it will be just a random list of available information. You can stuck in the next situation:
- $links has first 10 links
- $id has 3,4,5,7,9,11
It's just a list. Even if you have only this pure info (no other details), you can't properly associate it between of them by using shown source.
Here is minimum 1 simple solutions:
don't skip, don't merge, just add an empty array, and your final loop will be like this:
$assetid = "%assetid%";
for ($link as $key=>$final) {
if (count($final) && count($id[$key])) {
echo str_replace($assetid, $id[$key]['id'], $final['link']);
} else {
// some of needed arguments absent
}
}
Description not enough. Maybe try dump some variables?
foreach($array AS $final){
$assetid = "%assetid%";
//Check what is in $final
var_dump($final);
echo str_replace($assetid, $final['id'], $final['link']);
}

How to change value of one element to key in array?

How can I make value of one element into key in the same array
from this
[0]=>
array(2) {
["name"]=>
string(7) "segment"
["value"]=>
string(9) "Name Test"
}
to this
["segment"]=> "Name Test"
Try and run each item through a function or foreach loop assigning it as you want.
$res = array();
foreach($data as $item)
{
$res[$item['name']] = $item['value'];
}
Or through a function such as array_walk
$res = array();
array_walk($data, function($item, $key) use (&$res) {
$res[$item['name']] = $item['value'];
});
Simplifying (if you have one row indexed as '0'):
$array = array('0' => array('name'=>'segment'
'value'=>'Name Test'));
$new_array = array();
$new_array[$array[0]['name']] = $array[0]['value'];
print_r($new_array);

Create string to put in an IN statement from an array of arrays

I have an array of arrays that look like this:
array(40) {
[0]=>
array(2) {
["id"]=>
string(2) "ta"
["size"]=>
int(2)
[1]=>
array(2) {
["id"]=>
string(2) "tq"
["size"]=>
int(4)
....
I want to be able to get all the sizes in a way that I can do a query like this:
IN (2,4)
so... For each array, get the size key: IN (size,size,size...)
Thanks!
You could do something like this:-
$sizes = implode(',', array_map(function($v) { return $v['size']; }, $array));
Then just pass $sizes to your IN query
edit
In response to your comment below, you can use array_unique to remove duplicate sizes, eg:
$sizes = implode(',', array_unique(array_map(function($v) { return $v['size']; }, $array)));
Here you go:
$a = array("id"=>"ta","size"=>2);
$b = array("id"=>"tq","size"=>4);
$c = array($a,$b);
$in = array();
foreach ($c as $key=>$value) {
if(array_key_exists("size", $value)){
$in[] = $value["size"];
}
}
echo implode(",", $in);
$sizes = array();
foreach($array as $value) {
$sizes[] = $value['size'];
}
$query = implode(',', $sizes);
query ..." IN ($query) "..

How to search array item with given string

i have an array:
$mainArr = ["SRI", "AIS", "GOW","SRI#AIS","SRI#GOW", "SRI#GOW#AIS"];
$strArr = ["SRI"];
i want to search the main Array with the given string Array element so that if the string is matched it should get the corresponding key,value pair.
expected o/p would be:
Array[
0->SRI
3->SRI#AIS
4->SRI#GOW
5->SRI#AIS#GOW
]
Any ideas ?
Thanks,
Srinivas
$mainArr = array("SRI", "AIS", "GOW","SRI#AIS","SRI#GOW", "SRI#GOW#AIS");
$strArr = array("SRI");
foreach ($mainArr as $key => $value)
{
foreach ($strArr as $str)
{
if (strpos($value,$str) !== false) $rez[$key] = $value;
}
}
var_dump($rez);
output:
array(4) {
[0]=> string(3) "SRI"
[3]=> string(7) "SRI#AIS"
[4]=> string(7) "SRI#GOW"
[5]=> string(11) "SRI#GOW#AIS"
}
I thing i ll help u,,
$test=array();
$mainArr = array("SRI", "AIS", "GOW","SRI#AIS","SRI#GOW", "SRI#GOW#AIS");
$strArr = array("SRI");
foreach ($mainArr as $key => $value)
{
$temp = explode('#',$value);
//$temp = $temp[0];
if(in_array($temp[0],$strArr))
$test[$key]=$value;
}
echo "<pre><span style='color:black; font-size:19;'>";print_r($test);echo "</span></pre>";
Use array_filter:
function filter($element)
{
return strpos($element, 'SRI') !== false;
}
$mainArr = array("SRI", "AIS", "GOW","SRI#AIS","SRI#GOW", "SRI#GOW#AIS");
$filteredArr = array_filter($mainArr, 'filter');

Categories