-1
\$\begingroup\$

I have written the code below and I got the result what I wanted as below. But I needed pass to make the three-dimensional array for the result. Can I avoid to make three dimensional result? And I hope using only array_key_exists() and array_push() and unset().

The final result:

 Array
(
[0] => Array
    (
        [name] => Strawberry
        [id] => 10
    )

[1] => Array
    (
        [name] => Strawberry
        [id] => 60
    )

[2] => Array
    (
        [id] => 13
    )

[3] => Array
    (
        [name] => Apple
        [id] => 20
    )

[4] => Array
    (
        [name] => Apple
        [id] => 50
    )

[5] => Array
    (
        [id] => 28
    )

[6] => Array
    (
        [name] => Mandarin
        [id] => 30
    ))

The mid result:

  Array
(
[0] => Array
    (
        [0] => Array
            (
                [name] => Strawberry
                [id] => 10
            )

        [1] => Array
            (
                [name] => Strawberry
                [id] => 60
            )

    )

[1] => Array
    (
        [id] => 13
    )

[2] => Array
    (
        [0] => Array
            (
                [name] => Apple
                [id] => 20
            )

        [1] => Array
            (
                [name] => Apple
                [id] => 50
            )

    )

[3] => Array
    (
        [id] => 28
    )

[4] => Array
    (
        [0] => Array
            (
                [name] => Mandarin
                [id] => 30
            )

    ))

My code:

<?php

$array       = array(
    array(
        'name' => 'Strawberry',
        'id' => '10'
    ),
    array(
        'id' => '13'
    ),
    array(
        'name' => 'Apple',
        'id' => '20'
    ),
    array(
        'id' => '28'
    ),
    array(
        'name' => 'Mandarin',
        'id' => '30'
    ),
    array(
        'name' => 'Apple',
        'id' => '50'
    ),
    array(
        'name' => 'Strawberry',
        'id' => '60'
    )
);
$arraylength = count($array);
$result      = array();//仮の結果。結果として三次元配列になる。
$bararray    = array();// idだけの配列を抜き出す。


for ($j = 0; $j < $arraylength; $j++) {
    if (array_key_exists('id', $array[$j]) == true && array_key_exists('name', $array[$j]) != true) {
        $newarr       = array();
        $newarr['id'] = $array[$j]['id'];
        array_push($bararray, $newarr);
    }
}// idのみの配列を抜き出した。
$j = 0;
for ($i = 0; $i < $arraylength; $i++) {

    $newarr = array();
    for ($k = $i; $k < $arraylength; $k++) {
        if (array_key_exists('id', $array[$i]) == true && array_key_exists('name', $array[$i]) == true && array_key_exists('name', $array[$k]) == true && $array[$k]['name'] == $array[$i]['name']) {
            array_push($newarr, $array[$k]);
            if ($i != $k) {
                unset($array[$k]);
                $arraylength--;
            }
            ;
        }
    }

    if (!$newarr) {
        array_push($result, $bararray[$j]);
        $j++;
    } else {
        array_push($result, $newarr);
    }
}//仮の結果、三次元配列はここまで
print_r($result);
$realresult   = array();//求めたい結果
$resultlength = count($result);
for ($k = 0; $k < $resultlength; $k++) {
    $resultArraylength = count($result[$k]);
    if ($resultArraylength == 1) {
        if (is_array($result[$k]) == true && array_key_exists(0, $result[$k]) == false) {
            array_push($realresult, $result[$k]);
        } else {
            array_push($realresult, $result[$k]['0']);
        }

    } else {
        for ($m = 0; $m < $resultArraylength; $m++) {
            array_push($realresult, $result[$k][$m]);
        }
    }

}

?>
\$\endgroup\$

closed as off-topic by Sᴀᴍ Onᴇᴌᴀ, Ludisposed, t3chb0t, Graipher, Dannnno Jan 9 '18 at 16:40

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions containing broken code or asking for advice about code not yet written are off-topic, as the code is not ready for review. After the question has been edited to contain working code, we will consider reopening it." – Sᴀᴍ Onᴇᴌᴀ, Ludisposed, t3chb0t, Dannnno
If this question can be reworded to fit the rules in the help center, please edit the question.

  • \$\begingroup\$ This code is completely incoherent. You gave no description of what it's supposed to do and the output produces no discernible pattern. I believe your code is broken and therefore the question is off-topic for CR. The code does not produce the result you say it produces - not even close. \$\endgroup\$ – I wrestled a bear once. Jan 7 '18 at 8:05
  • 1
    \$\begingroup\$ Can you please add more explanation about the purpose of this code? We're looking for some background information, context, summary. The text in your question is also hard to understand, I don't understand what you are asking. Can you please clarify? \$\endgroup\$ – janos Jan 7 '18 at 16:03
  • \$\begingroup\$ @Iwrestledabearonce. Okay, sorry about my description was unclear. I wanted to do two dimensional array without making three-dimensinal array. My output was totally different than this 3v4l.org/BS6Jc ?Anyway thanks for your comment. \$\endgroup\$ – kimi Tanaka Jan 7 '18 at 16:05
  • 1
    \$\begingroup\$ @kimiTanaka saying you want a 2d array instead of a 3d array does not explain what the code does. if your output is different then your code is different as 3v4l executes the code in all major versions of php. make sure you copied the code correctly because that is what this code produces. \$\endgroup\$ – I wrestled a bear once. Jan 7 '18 at 16:18
  • 1
    \$\begingroup\$ @kimiTanaka your code produces an array, you have said that several times. you are still not explaining what it does. is it supposed to sort an array? group items in the array? produce a specific pattern? \$\endgroup\$ – I wrestled a bear once. Jan 7 '18 at 16:43
2
\$\begingroup\$

You can iterate (and reduce with each pass) the input array and group the like-names in the result array. I am assuming all of the id values are already in the correct order. See inline comments for how it works.

Code: (Demo)

$array=[
    ['name'=>'Strawberry','id'=>'10'],
    ['id'=>'13'],
    ['name'=>'Apple','id'=>'20'],
    ['id'=>'28'],
    ['name'=>'Mandarin','id'=>'30'],
    ['name'=>'Apple','id'=>'50'],
    ['name'=>'Strawberry','id'=>'60']
];

while($first=current($array)){  // while $array is not empty, grab the first subarray
    if(isset($first['name'])){  // if the grabbed subarray has a 'name' key
        foreach($array as $i=>$sub){  // perform full scan of $array 
            if(isset($sub['name']) && $sub['name']===$first['name']){
                $result[]=$sub;  // store subarrays with matching name value
                unset($array[$i]);  // remove stored subarray from $array
            }
        }
    }else{
        $result[]=array_shift($array);  // no 'name' key, just store and remove from $array
    }
}
var_export($result);

Output:

array (
  0 => 
  array (
    'name' => 'Strawberry',
    'id' => '10',
  ),
  1 => 
  array (
    'name' => 'Strawberry',
    'id' => '60',
  ),
  2 => 
  array (
    'id' => '13',
  ),
  3 => 
  array (
    'name' => 'Apple',
    'id' => '20',
  ),
  4 => 
  array (
    'name' => 'Apple',
    'id' => '50',
  ),
  5 => 
  array (
    'id' => '28',
  ),
  6 => 
  array (
    'name' => 'Mandarin',
    'id' => '30',
  ),
)
\$\endgroup\$
  • \$\begingroup\$ Thank you! It's more concise than I did. I think I need to get used to the function of PHP. I really appreciate it. \$\endgroup\$ – kimi Tanaka Jan 8 '18 at 8:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.